Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  49] [ 2]  / answers: 1 / hits: 22619  / 6 Years ago, sun, january 21, 2018, 12:00:00

I've started splitting some code into presentational/container components and I'd like to call a function in the child/presentational component and pass both the event and some sort of prop back to the parent.



Parent:



class Parent extends Component{
constructor(props) {
super(props);
this.state = {}
this.reroll = this.reroll.bind(this);
}

test(key, e){
console.log(key, e)
}
render() {
return <Child test={()=>this.test} />
}
}


Child:



var Child = () => {
return (
<select onChange={props.test('test-key')}>
<option value='1'> Option 1 </option>
//etc...
</select>
)
}


Normally, when I had my code all in one place I would write the onChange function like this.



<select onChange={props.test.bind(this, 'test-key')}>


But binding this in the child causes it to no longer function. No other props passed to this function get returned to the parent. Is there any way that I can write this such that I can get back 'test-key'?


More From » reactjs

 Answers
9

You need to put function call inside callback of onChange event.



 <select onChange={()=>props.test('test-key')}>


In this way you can also pass event object too.



 <select onChange={(event)=>props.test(event,'test-key')}>

[#55407] Wednesday, January 17, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aliah

Total Points: 118
Total Questions: 132
Total Answers: 94

Location: Tajikistan
Member since Fri, Sep 11, 2020
4 Years ago
;