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

cod*_*ork 4 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>
       }
   });
Run Code Online (Sandbox Code Playgroud)

win*_*elt 5

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

<ChildComponent foo={this.state.data} />
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过在ChildComponent内部访问它this.props.foo

说明:在ChildComponent内部,this.state.someData指的是ChildComponent状态。而且您的孩子没有状态。(顺便问一下)

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

更好地初始化父状态

return { data : null };
Run Code Online (Sandbox Code Playgroud)