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

时间:2015-06-25 11:19:25

标签: javascript reactjs reactjs-flux

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

下面是我的应用组件。我正在尝试通过循环子组件 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>
                )
            }
    });

1 个答案:

答案 0 :(得分: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

相关问题