Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

下面两种传参方式

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

下面不传参改变this指向

class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }
 
  render() {
    //  这个语法确保了 `this` 绑定在  handleClick 中
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
  }
}
查阅文档说:
使用这个语法有个问题就是每次 LoggingButton 渲染的时候都会创建一个不同的回调函数。在大多数情况下,这没有问题。然而如果这个回调函数作为一个属性值传入低阶组件,这些组件可能会进行额外的重新渲染。我们通常建议在构造函数中绑定或使用属性初始化器语法来避免这类性能问题。

问题一:那么我是不是可以认为在用箭头函数传参时也会引起重新渲染,所以传参方式最好是下面这种?

<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

问题二:然后还有就是改变this指向时是否也可以这么写?

<button onClick={this.deleteRow.bind(this)}>Delete Row</button>

但是我看文档用bind改变this指向时,直接在constructor初始化时调用this

class Reservation extends React.Component {
      constructor(props) {
        super(props);
        this.handleInputChange = this.handleInputChange.bind(this);
      }

如上两个问题


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

  1. 在渲染的时候箭头函数也会创建一个不同的回调函数,也会引起重新渲染。
  2. 放在constructor里和直接在调用的地方bind都可以,放在constructor里是为了方便页面中有多处重复调用时不用每次都去bind一次

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...