【问题标题】:Access a component's children props outside the parent component in react在反应中访问父组件之外的组件的子道具
【发布时间】:2021-10-11 10:17:26
【问题描述】:

我在 react 中有一个主页面组件,其渲染功能如下所示

const MainPage = () => {
    return (
         <>
              <Component1 />
              <Component2 />
         </>
    )
}

并且组件有一些输入

const Component1 = () => {
    const [val1, setVal1] = React.useState("");
    const [val2, setVal2] = React.useState("");
    return (
         <>
              <input type="text" value={val1} onChange={setVal1} />
              <input type="text" value={val2} onChange={setVal2} />
         </>
    )
}

我的问题是如何在 MainPage 组件中获取值 val1 和 val2? 提前致谢

【问题讨论】:

  • 我觉得你不能那样做,你应该在 MainPage 组件中有状态值,或者如果你需要使用这些值你必须使用上下文 API
  • @Nacho 我相信这种方法会导致不必要的螺旋桨钻孔。所以想确定是否有其他更好的方法。

标签: javascript reactjs react-hooks


【解决方案1】:

在您的 React 项目中使用 Redux 或 Context API。顺便说一句,您可以调用该函数来获取子组件变量的值。

使用类的示例反应

class Parent extends Component {
  constructor() {
    this.state = {
      value: ''
    };
  }

  //...

  handleChangeValue = e => this.setState({value: e.target.value});

  //...

  render() {
    return (
      <Child
        value={this.state.value}
        onChangeValue={this.handleChangeValue}
      />
    );
  }
}

class Child extends Component {
  //...

  render() {
    return (
      <input
        type="text"
        value={this.props.value}
        onChange={this.props.onChangeValue}
      />
    );
  }
}

【讨论】:

  • 我不知道这如何解决我的问题。您刚刚维护了父组件级别的状态并将其作为道具传递给子组件
【解决方案2】:

你不能。 React 基于Unidirectional Data Flow

因此,要解决您的问题,您必须定义一个将从子级调用的事件。

const MainPage = () => {
    const [val1, setVal1] = React.useState("");
    const [val2, setVal2] = React.useState("");
    return (
         <>
              <Component1 val1={val1} onChange1={setVal1} val2={val2} onChange2={setVal2} />
              <Component2 />
         </>
    )
}

和组件1

const Component1 = ({val1, onChange1, val2, onChange2}) => {
    return (
         <>
              <input type="text" value={val1} onChange={onChange1} />
              <input type="text" value={val2} onChange={onChange2} />
              />
         </>
    )
}

【讨论】:

  • 这个方法我已经知道了。我认为这涉及不必要的支柱钻孔。谢谢(你的)信息。只会继续这种方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-08
  • 2016-06-02
  • 2019-12-29
  • 1970-01-01
  • 2018-05-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多