将值从子节点传递给父组件 [英] pass value from child to parent component in react

查看:71
本文介绍了将值从子节点传递给父组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有组件A和B.组件一个传递状态作为组件的prop,说它名为show

I have component A and B. Component A pass state as prop to component, says it's named show

所以在我的组件B的渲染函数中它将是这样的

so in my component B's render function it will be like this

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

但我现在如何关闭它?我必须将组件B中的标志传递给父级?据我所知它反应你可以将东西传回父母。

But how I close it now? I have to pass a flag from component B to the parent? as I know it react you can pass stuff back to parent.

推荐答案

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

In order to pass data from a child to a parent, the parent needs to pass a function capable of handling that data to the child.

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>
    }

});

还有其他处理数据的方法,在创建数据存储时可能值得你去存储全局变量并处理各种事件。通过这种方式,您可以保持应用程序的数据流单向。然而,在较小规模的情况下,这个解决方案就足够了。

There are other ways of handling data, and it might be worth your while creating a data store to store global variables and handle various events. In this way you would keep the data flow of your application one way. In smaller scale cases however, this solution should suffice.

这篇关于将值从子节点传递给父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆