首页 > 试题广场 >

在 React 项目中,绑定 `this`&...

[单选题]
在 React 项目中,绑定 `this` 通常有如下两种写法:
class LoggingButton extends React.Component {
    handleClick = () => {
    console.log('this is:', this)
}
render() {
    return (
        <button onClick={this.handleClick}>
        Click me
      </button>
        )
    }
}
class LoggingButton extends React.Component {
    constructor () {
        super(props)
        this.handleClick = this.handleClick.bind(this)
    }
    handleClick () {
        console.log('this is:', this)
    }
    render() {
        return (
            <button onClick={this.handleClick}>
                Click me
          </button>
        )
    }
}
哪种写法运行效率更高?
  • 箭头函数式
  • 非箭头函数式
  • 运行效率相同
  • 无法确定
箭头函数找this的时候还得从上下文推断,使用bind在构造函数种是从原型上面去修改的,应该快一点
发表于 2021-09-20 19:50:52 回复(0)