我已经问了类似的问题,但我遇到了新问题)。我想在点击子组件时执行父组件的功能。
var Fructs = ['banana', 'mango', 'potato'];
var Kaka = React.createClass({
render() {
return <div onClick={this.props.onClick}> Hell o forld </div>
}
});
var Application = React.createClass({
handle() {
console.log("took took");
},
render() {
console.log(this.props);
var mass = Fructs.map(function(data, index) {
return <Kaka key={index} onClick={handle.bind(this)}/>
});
return (
<div>
{ mass }
</div>
);
}
});
var App = React.createClass({
render() {
return (
<div>
<Application />
</div>
);
}
});
React.render(<App/>, document.getElementById('app'));
insertAfter 如果儿童成分是一个,所有工作都是完美的。但是,如果我尝试生成子组件列表它不起作用。错误的日志写入“找不到”。 我发现类似的问题Example on CodePen,但我做的是wronп(。请告诉我做错了什么?
答案 0 :(得分:1)
您应该为.map
回调设置此项,同时您handle
是方法,为了获得它,您需要在更改this.handle
之后使用.map
var mass = Fructs.map(function(data, index){
return <Kaka key={index} onClick={ this.handle.bind(this) } />
^^^^^^^^^^^ - get Component method
}, this);
^^^^ - callback context
var Fructs = ['banana', 'mango', 'potato'];
var Kaka = React.createClass({
render() {
return <div onClick={this.props.onClick}>
Hell o forld
</div>
}
})
var Application = React.createClass({
handle() {
console.log("took took");
},
render() {
var mass = Fructs.map(function(data, index){
return <Kaka key={index} onClick={ this.handle.bind(this) } />
}, this);
return <div>
{ mass }
</div>
}
})
var App = React.createClass({
render() {
return <div>
<Application />
</div>
}
})
ReactDOM.render(<App />, document.getElementById('app'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
&#13;