解释了将数据从父传递到子传输的概念,反之亦然。
import React, { Component } from "react"; import ReactDOM from "react-dom"; // taken refrence from https://gist.github.com/sebkouba/a5ac75153ef8d8827b98 //example to show how to send value between parent and child // props is the data which is passed to the child component from the parent component class Parent extends Component { constructor(props) { super(props); this.state = { fieldVal: "" }; } onUpdateParent = val => { this.setState({ fieldVal: val }); }; render() { return ( // To achieve the child-parent communication, we can send a function // as a Prop to the child component. This function should do whatever // it needs to in the component e.g change the state of some property. //we are passing the function onUpdateParent to the child <div> <h2>Parent</h2> Value in Parent Component State: {this.state.fieldVal} <br /> <Child onUpdate={this.onUpdateParent} /> <br /> <OtherChild passedVal={this.state.fieldVal} /> </div> ); } } class Child extends Component { constructor(props) { super(props); this.state = { fieldValChild: "" }; } updateValues = e => { console.log(e.target.value); this.props.onUpdate(e.target.value); // onUpdateParent would be passed here and would result // into onUpdateParent(e.target.value) as it will replace this.props.onUpdate //with itself. this.setState({ fieldValChild: e.target.value }); }; render() { return ( <div> <h4>Child</h4> <input type="text" placeholder="type here" onChange={this.updateValues} value={this.state.fieldVal} /> </div> ); } } class OtherChild extends Component { render() { return ( <div> <h4>OtherChild</h4> Value in OtherChild Props: {this.props.passedVal} <h5> the child can directly get the passed value from parent by this.props{" "} </h5> </div> ); } } ReactDOM.render(<Parent />, document.getElementById("root"));
您应该学习Redux和ReactRedux库。它将在一个商店中构建您的状态和道具,您可以稍后在组件中访问它们。
使用React&gt; = 16.3,您可以使用ref和forwardRef从父级访问子级DOM。不要再使用旧的参考方式了。 以下是使用您的案例的示例:
import React, { Component } from 'react'; export default class P extends React.Component { constructor (props) { super(props) this.state = {data: 'test' } this.onUpdate = this.onUpdate.bind(this) this.ref = React.createRef(); } onUpdate(data) { this.setState({data : this.ref.current.value}) } render () { return ( <div> <C1 ref={this.ref} onUpdate={this.onUpdate}/> <C2 data={this.state.data}/> </div> ) } } const C1 = React.forwardRef((props, ref) => ( <div> <input type='text' ref={ref} onChange={props.onUpdate} /> </div> )); class C2 extends React.Component { render () { return <div>C2 reacts : {this.props.data}</div> } }
看到 参考文献 和 ForwardRef 有关refs和forwardRef的详细信息。
第一个解决方案,用 将状态保持在父组件中 是的 正确的 。但是,对于更复杂的问题,你应该考虑一些问题 国家管理图书馆 , 终极版 是最常用的反应。