Reputation: 247
i've got this 2 components and i'm wondering how to call passed function. Because if i pass it -> i've got a reference to it in a child so the problem appears when i want to pass a paremeter to it - because its immediately calling ( this is clear ).
class Parent extends Component {
....
fn = (arg) => {console.log(arg)}
render(){
return (
<Child myPassedFn={this.fn}>delete</button>
)
}
}
class Child extends Component {
render(){
return (
<button onClick={this.props.myPassedFn('lul')}>delete</button>
)
}
}
in this way as soon as component Child
renders, myPassedFn
will execute
So is this a right approach to make it happen ? Because i want to make thinks, you know, in a most clear and proper way
class Child extends Component {
childFn = () => {
this.props.myPassedFn('this is how i could pass, you little..')
}
render(){
return (
<button onClick={this.childFn}>delete</button>
)
}
}
Upvotes: 0
Views: 44
Reputation: 104369
You can write it like this also:
onClick={() => this.props.myPassedFn('lul')}
Onclick
except a method
, and the way you are using is, method calling, it will return
the value.
You can use the 2nd way also, above line is just the shorthand for that.
Upvotes: 1