I have the following two components:
class A extends Component {
_onDelete(id) {
this.props.deleteItem(id);
}
render() {
return <B onDelete={this._onDelete}/>;
}
}
class B extends Component {
const onDelete= {this.props};
let id = this.props.item.id;
render() {
return <div onClick={onDelete}>Hello</div>;
}
}
I don't want to bind this
(component B context) to the function, I only want to pass id
to _onDelete
.
I tried these approaches:
Arrow function:
return <div onClick={() => onDelete(id)}>Hello</div>;
context
in _onDelete
changes to B, and I don't have access to this.props.deleteItem
anymore.
Passing by event:
return <div onClick={onDelete} itemId={id}>Hello</div>; _onDelete(event) { this.props.deleteItem(event.target.itemId); }
event.target.itemId
is undefined
How can I pass the itemId
to A
's function, without binding this
to it ?
class A extends Component {
_onDelete = (id) => {
this.props.deleteItem(id);
}
render() {
return <B onDelete={this._onDelete}/>;
}
}
This way _onDelete will be available with A context. Just call it like this in B
class B extends Component {
let id = this.props.item.id;
render() {
return <div onClick={() => this.props.onDelete(id)}>Hello</div>;
}
}
Your syntax is not quite correct, but I guess it's a problem here, not in your actual code. If you don't want to call .bind(this)
, then you can pass an arrow function to onDelete
which calls _onDelete
:
<B onDelete={id => this._onDelete(id)}/>
The better solution would be to directly pass this.props.deleteItem
, if that's all that _onDelete
is calling:
<B onDelete={this.props.deleteItem}/>
In B
you'd have to pass a custom function as well:
return <div onClick={() => onDelete(id)}>Hello</div>;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.