【问题标题】:bind component method from callback to child component将组件方法从回调绑定到子组件
【发布时间】:2015-09-11 23:23:13
【问题描述】:

我是反应 js 的新手,无法在 foreach 循环中将父组件方法传递给子组件。我的代码是

下面是我的 App 组件。我正在尝试通过循环子组件 RecordRow 来显示我从 api 中获取的数据。

var APP=
    React.createClass({
 qwerty: function(name) {
            alert("Qwerty");
            alert(name);

        },
        render:function(){      /* table header and border */
                //alert("result2:"+this.state.result)
                var rows = [];
                var data = this.state.result;
                if(data){
                    data.forEach(function(data2,i){
                        rows.push(<RecordRow  data={data2}  key={i} fun ={this.qwerty}/>)
                    });
                }
                return(
                    <table className="table table-bordered">
                    <tr>
                    <th>ZipCode</th>
                    <th>ShortCode</th>
                    <th>City</th>
                    <th>State</th>
                    <th>TaxCode</th>
                    <th>UserId</th>
                    <th></th>
                    </tr>
                    <tbody>
                    {rows}
                     </tbody>
</table>
<div className="modal">
.
. //modal popup code
.
</div>
)

}
});

当我点击下面的编辑按钮时,我想将 Record Row 的数据对象发送回我的父组件并在那里显示在警报中。我如何实现它?

var RecordRow=
    React.createClass({
            submit:function(){
                if(this.props.fun) {
                    alert("fun")
                    this.props.fun("Harsha");
                }
            },
            render:function() {
                return (

                    <tr>
                    <td>{this.props.data.ZipCode}</td>
                    <td>{this.props.data.ShortCode}</td>
                    <td>{this.props.data.City}</td>
                    <td>{this.props.data.State}</td>
                    <td>{this.props.data.TaxCode}</td>
                    <td>{this.props.data.UserId}</td>
                    <td><input type="button" className="btn btn-primary" data-toggle="modal" data-target="#modaling" onClick={this.submit} value ="EDIT"/></td>
                    </tr>
                )
            }
    });

【问题讨论】:

    标签: javascript reactjs reactjs-flux


    【解决方案1】:

    您的代码中有一些错误:

    1. you try to return two different react elements in `App`->`render()`
    2. you are using `result` but you don't define a state
    3. you didn't bind the context to the callback method, so this.qwerty is undefined
    

    我用固定版本创建了一个fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多