繁体   English   中英

在反应中访问父组件之外的组件的子道具

[英]Access a component's children props outside the parent component in react

我在反应中有一个主页组件,其渲染 function 看起来像这样

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

Component 有一些输入

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? 提前致谢

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

使用 Class 的示例 React

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}
      />
    );
  }
}

你不能。 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} />
              />
         </>
    )
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM