【问题标题】:How to pass value from parent component to child component (react)如何将值从父组件传递给子组件(反应)
【发布时间】:2015-10-31 22:47:42
【问题描述】:

我是学习 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>
       }
   });

【问题讨论】:

    标签: javascript ajax reactjs


    【解决方案1】:

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

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

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

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

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

    最好用

    初始化父状态
    return { data : null };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-04
      • 2019-04-02
      • 1970-01-01
      • 1970-01-01
      • 2021-06-30
      • 2020-10-21
      • 2020-03-30
      • 2018-05-01
      相关资源
      最近更新 更多