如何将值从父组件传递给子组件(反应)

时间:2015-10-31 22:47:43

标签: javascript ajax reactjs

我是学习React的新手,我正试图将我从ParentComponent(通过输入框)内的用户输入获得的值传递到ChildComponent - 我将使用用户输入值来运行AJAX调用。

我认为通过替换ParentComponent中的状态会起作用 - 但我仍然无法在ChildComponent中抓住它。

我也只希望ChildComponent在收到ParentComponent的输入值后才能运行/渲染(这样我就可以运行AJAX调用然后渲染......)。

任何提示?

var ParentComponent = React.createClass({
     getInitialState: function() {
         return {data: []};
     },

    handleSearch: function(event) {
        event.preventDefault();
        var userInput = $('#userInput').val();
        this.replaceState({data: userInput});
    },

    render: function() {
        return (
            <div>
                <form>
                    <input type="text" id="userInput"></input>
                    <button onClick={this.handleSearch}>Search</button>
                </form>
                <ChildComponent />
                {this.props.children}
            </div>
          );
        }
    });

var ChildComponent = React.createClass({
   render: function() {
        return <div> User's Input: {this.state.data} </div>
       }
   });

1 个答案:

答案 0 :(得分:4)

您应该将父状态作为道具传递给您的孩子:将父渲染中的子组件更改为:

<ChildComponent foo={this.state.data} />

然后您可以通过this.props.foo在ChildComponent中访问它。

说明:在ChildComponent内部,this.state.someData引用ChildComponent状态。而你的孩子没有国家。 (顺便说一句,这很好)

另外:this.setState()可能比this.replaceState()好。

最好用

初始化父状态
return { data : null };
相关问题