javascript - 在父级调用函数并将 `this` 绑定(bind)到子级?

标签 javascript reactjs ecmascript-6

我想做的是从其子元素调用在父元素中定义的函数,但将 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/

相关文章:

javascript - 使用 switch case 跟踪数组的全局索引

reactjs - 通过解构可以使这个分配变得更简单吗?

javascript - 正确卸载 react 组件

javascript - 如何在预览图像上添加复选框

reactjs - 无法将 d3-tip 或 d3-hexbin 导入 React 组件

javascript - 与容器 div 重叠的传单 map

javascript - 从 "run time"中的外部脚本加载 React JS 组件

JavaScript 定时器用法

javascript - JavaScript 中的可变变量

javascript - 访问 ng-repeat 的第一个元素