by positivecomment · 9y ago · 0 comments
render() {
const views = this .props.dataList.map((d, i) => {
return <Data data={d} index={i} onDelete={this.handleDelete} />
});
}
handleDelete(index) {
//...
}
I guess they just call that function from within the Data component with the correct parameter. But then, Data component needs to know how to call that function. Is there a better way?[1] https://facebook.github.io/react/docs/handling-events.html
[2] https://babeljs.io/docs/plugins/transform-class-properties/
One is to bind the callback function to a certain index in advance and then supply that callback to your child via props so it already knows the relevant index and doesn't need calling with any extra parameters. The trouble with this one is that it creates a new function every time, which is inefficient in itself and horrible if it winds up causing your child to rerender because props changed even though in practice you're passing an identical function every time.
The other is to supply a callback where the child component is responsible for supplying the extra index information when it calls the function, either by directly passing the index as a parameter or via an indirect route such as using data-* attributes as 'kentor mentioned. This is more efficient, but it creates tighter coupling between the child and parent components.
In practice, it seems most projects adopt the second strategy because the tighter coupling is usually much less of a problem in practice than the performance penalty, but neither solution is ideal. Unfortunately, JavaScript's semantics don't make it easy to have the equivalent of a "deep equal" comparison on functions that would return true for two copies of the same function with the same bound values.
Yep
> Is there a better way?
We're experimenting with some other options internally. Once we have a better sense of what works best, we will post another article on our learnings :)
return ( <Data value={d} index={i} deleteDataAt={deleteDataAt} /> );
Then your onClick in the child would be: onClick = (_e) => this.props.deleteDataAt(this.props.index);
Correct me if I'm missing anything!
You're not missing anything :) That approach also works. The important point is that you have to pass the extra index prop down to the child to avoid the bind in render.
If you did this.foo = this.foo.bind(this, props.bar) in the constructor then it would be the same function each time.
In general binding like that in the constructor works only if you depend on props, but at that point, there isn't a need to bind at all since you can just reference the prop in the callback.