我想做的是从其子元素调用在父元素中定义的函数,但将 this
绑定(bind)到调用函数的子元素,而不是函数运行的父元素。
有没有办法做到这一点,如果是的话,这会是一种反模式吗?谢谢。
传递给子函数的父函数
onSelect = (event => {
// Some code where `this` is the scope of the child calling the function
// Not the scope of the parent where the function is defined
}
父渲染函数
render() {
return (
<Child onSelect={this.onSelect} />
)
}
子渲染函数
render() {
return (
<button onClick={this.props.onSelect.bind(this)} />
)
}
最佳答案
问题是您将 onSelect
定义为箭头函数,因此它关闭 this
而不是使用它被调用的 this
和。只需将其设为方法或非箭头函数即可:
class Parent extends React.Component {
onSelect() {
console.log(this.constructor.name);
console.log(this.note);
}
render() {
return <Child onSelect={this.onSelect} />;
}
}
class Child extends React.Component {
constructor(...args) {
super(...args);
this.note = "I'm the child";
}
render() {
return (
<button onClick={this.props.onSelect.bind(this)}>Click Me</button>
);
}
}
ReactDOM.render(
<Parent />,
document.getElementById("root")
);
<div id="root"></div>
<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>
但是您可能会考虑绑定(bind) onSelect
一次 而不是重复绑定(bind)(例如,不在 render
中),也许在 Child
的构造函数。但只有当 render
被称为 lot 时才真正重要。例如:
class Parent extends React.Component {
onSelect() {
console.log(this.constructor.name);
console.log(this.note);
}
render() {
return <Child onSelect={this.onSelect} />;
}
}
class Child extends React.Component {
constructor(...args) {
super(...args);
this.note = "I'm the child";
this.onSelect = this.props.onSelect.bind(this);
}
render() {
return (
<button onClick={this.onSelect}>Click Me</button>
);
}
}
ReactDOM.render(
<Parent />,
document.getElementById("root")
);
<div id="root"></div>
<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>
关于javascript - 在父级调用函数并将 `this` 绑定(bind)到子级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46991871/