如何在React中从父组件传递值到子组件

7
我刚开始学习React,在我的ParentComponent中,我通过输入框获得了一个值,现在想将这个值传递给我的ChildComponent,并使用它来运行AJAX调用。我尝试过通过替换ParentComponent中的状态来实现,但是我仍然无法在ChildComponent中获取它。
我希望只有在从ParentComponent接收到输入值后才渲染/运行ChildComponent(以便我可以运行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个回答

8
您需要将父组件的状态作为属性传递给子组件:在父组件的渲染中更改您的子组件如下所示:
<ChildComponent foo={this.state.data} />

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

解释:在 ChildComponent 内部,this.state.someData 指的是 ChildComponent 状态。而你的子组件没有状态。(顺便说一句,这很好)

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

最好使用以下方式初始化父级状态:

return { data : null };

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接