【问题标题】:Unable to pass a parent component's state to its child component无法将父组件的状态传递给其子组件
【发布时间】:2019-01-26 16:21:59
【问题描述】:

我无法将父组件的状态传递给其子组件。

我尝试将整个父母的状态传递给孩子,但是,状态本身的内容是undefined。 另外,我也尝试过类似的使用 props,但效果也不好。


//parent.js

state = {
  messages: [],
  roomId: this.props.navigation.getParam('roomId')
}

renderImageAction = () => {
  return <ImageAction roomId={this.state.roomId} />
}

return(<GiftedChat renderActions={this.renderImageAction}/>)

//child.js
DataBase.saveImage(this.props.roomId).then(alert('done'));  

我希望将状态或值传递给子组件,并且值将在那里可用。

【问题讨论】:

    标签: reactjs react-native react-native-gifted-chat


    【解决方案1】:

    在我看来,这是理解这件事的最简单方法。希望这会有所帮助。

    class Parent extends React.Component {
    
      constructor(props) {
    
        super(props);
    
        this.state = {
    
          fieldVal: ""
    
        }
    
      }
    
      onUpdate = (val) => {
    
        this.setState({
    
          fieldVal: val
    
        })
    
      };
    
      render() {
    
        return (
    
          <div>
    
            <h2>Parent</h2>
    
            Value in Parent Component State: {this.state.fieldVal}
    
            <br/>
    
            <Child onUpdate={this.onUpdate} />
    
            <br />
    
            <OtherChild passedVal={this.state.fieldVal} />
    
          </div>
    
        )
    
      }
    
    }
    
    
    
    class Child extends React.Component {
    
      constructor(props) {
    
        super(props);
    
        this.state = {
    
          fieldVal: ""
    
        }
    
      }
    
      update = (e) => {
    
        console.log(e.target.value);
    
        this.props.onUpdate(e.target.value);
    
        this.setState({fieldVal: e.target.value});
    
      };
    
      render() {
    
        return (
    
          <div>
    
            <h4>Child</h4>
    
            <input
    
              type="text"
    
              placeholder="type here"
    
              onChange={this.update}
    
              value={this.state.fieldVal}
    
            />
    
          </div>
    
        )
    
      }
    
    }
    
    class OtherChild extends React.Component {
    
      render() {
    
        return (
    
          <div>
    
            <h4>OtherChild</h4>
    
            Value in OtherChild Props: {this.props.passedVal}
    
          </div>
    
        )
    
      }
    
    }
    
    React.render(
    
      <Parent />,
    
      document.getElementById('react_example')
    
    );

    【讨论】:

      猜你喜欢
      • 2019-04-02
      • 2017-05-31
      • 2019-02-17
      • 2022-07-15
      • 2014-12-18
      • 2019-08-15
      • 1970-01-01
      • 2020-06-21
      • 2020-07-04
      相关资源
      最近更新 更多