繁体   English   中英

将值从子级传递到父级组件中

[英]pass value from child to parent component in react

我有组件A和组件B。组件A的传递状态作为组件的支持,称其为show

所以在我的组件B的render函数中,它将像这样

{this.props.show &&
   <div>popup content</div>
}

但是我现在如何关闭呢? 我必须将标志从组件B传递给父对象吗? 据我所知,您可以将东西传回给父母。

为了将数据从子级传递到父级,父级需要将能够处理该数据的功能传递给子级。

var Parent = React.createClass({

    getData: function(data){
         this.setState({childData: data});     
    }

    render: function(){
        return(
            <Child sendData={this.getData} />
        );
    }

});

var Child = React.createClass({

    textChange: function(event){
        this.setState({textString: event.target.value});
    }

    buttonClick: function(){
        this.props.sendData(this.state.textString);
    }

    render: function(){
        <div>
        <input type="text" value={this.state.textString} 
               onChange={this.textChange}/>
        <button onClick={this.buttonClick}
        </div>
    }

});

还有其他处理数据的方法,在创建数据存储区以存储全局变量和处理各种事件时,可能值得您这样做。 这样,您将使应用程序的数据流保持一种方式。 但是,在较小规模的情况下,此解决方案就足够了。

使用eventBus分别从子组件/父组件发送/接收日期。

下面的例子:

class Date extends Component {

 constructor(props) {
    super(props);
    this.state = {
        date:'',           
}
   this.callback = this.callback.bind(this); // register callback method
}

callback(date){    // callback method to receive data
    this.setState({date: date});
}


componentDidMount(){
    EventBus.on("date", this.callback);
}
render() {

<div>
      {this.state.date}
</div>
  }
} 

来自任何其他组件

 handleDayClick(day) {
         EventBus.publish("date", day);
  }

https://github.com/arkency/event-bus

暂无
暂无

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

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