Reputation: 75
I already asked similar question but i got new a problem). I want while click on child-component perform function of parent-component.
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'));
Example on CodePen All work perfect if child-component is one. But if i try generate list of child-component it doesn't work. Error's log write that "this" isn't find. I find similar a problem doc React, but i do it wronп (. Please, tell what i do wrong?
Upvotes: 0
Views: 105
Reputation: 77482
You should set this for .map
callback., also you handle
is method, in order to get it you need use this.handle
after changes .map
should looks like this
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'));
<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>
Upvotes: 1