将组件方法从回调绑定到子组件

bind component method from callback to child component

我是 React js 的新手,无法将父组件方法传递给 foreach 中的子组件 loop.My 代码是

下面是我的 App Component.I 我试图通过循环子组件 [=18] 在 table 中显示我从 api 获得的数据=]RecordRow.

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>
)

}
});

当我点击下面的编辑按钮时,我想将记录行的数据对象发送回我的父组件并在警报中显示它there.How我实现了吗?

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>
                )
            }
    });

您的代码有一些错误:

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