首页 > 解决方案 > 调用回调函数的函数应该绑定吗?

问题描述

Parent如果我从to传递一个回调函数GrandChild,应该handleClick绑定在Childand中GrandChild吗?

父.js

class Parent extends React {
  constructor() {
    super();

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    console.log('Clicked!');
  }

  render() {
    return (
      <Child onClick={this.handleClick} />
    );
  }
}

Child.js

class Child extends React {
  constructor() {
    super();

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    const { onClick: callback } = this.props;

    callback();
  }

  render() {
    return (
      <GrandChild onClick={this.handleClick} />
    );
  }
}

GrandChild.js

class GrandChild extends React {
  constructor() {
    super();

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    const { onClick: callback } = this.props;

    callback();
  }

  render() {
    return (
      <div onClick={this.handleClick} />
    );
  }
}

标签: javascriptreactjsecmascript-6

解决方案


箭头功能更好。并且上下文this将自动绑定。

handleClick = () => {}

内联函数不好(可能出现不必要的渲染)。最好是这样:

handleClick = (someData) => this.props.handeClick(someData)

onClick={this.handleClick}

推荐阅读