Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript react样板中的绑定事件处理程序_Javascript_Reactjs_React Boilerplate - Fatal编程技术网

Javascript react样板中的绑定事件处理程序

Javascript react样板中的绑定事件处理程序,javascript,reactjs,react-boilerplate,Javascript,Reactjs,React Boilerplate,我知道有4种绑定事件处理程序的方法。第一种方法是通过在render()中的DOM元素中进行绑定: 第三种是通过类构造函数内的绑定: constructor(props) { super(props) this.state = { message: "Click" } **this.clickHandler = this.clickHandler.bind(this);** } r

我知道有4种绑定事件处理程序的方法。第一种方法是通过在
render()中的DOM元素中进行绑定:

第三种是通过类构造函数内的绑定:

constructor(props) {
        super(props)
        this.state = {
             message: "Click"
        }
        **this.clickHandler = this.clickHandler.bind(this);**
    }
render() {
        return (
            <div>
                <div>{this.state.message}</div>
                **<button onClick = {this.clickHandler}>Event</button>**
            </div>
        )
    }
那么哪种方式最好呢?

据我所知:-

  • 1st情况下,将在React应用程序的每个渲染上创建一个新的绑定的
    clickHandler
  • 2nd情况下,将创建一个新的匿名箭头函数,该函数在React应用程序的每个渲染上内部调用
    clickHandler
    (执行时)
  • 3rd和4th都更好,因为它们会导致一次性创建
    clickHandler
    。它们位于渲染流之外

您认为第三和第四之间的哪一个是编译和执行速度最快的?这可以归结为箭头函数和常规函数的性能。我还没有研究过。我认为arrow函数是我想要使用的函数,因为我甚至跳过了一次性绑定函数的创建。但我并不确定这会带来多大的性能提升。这非常有帮助。您的“最佳”客观指标是什么?@TylerH我的目的是找出哪种方法最适合同步处理,哪种方法开发得最快
<button onClick = {() => this.clickHandler()}>Event</button>
constructor(props) {
        super(props)
        this.state = {
             message: "Click"
        }
        **this.clickHandler = this.clickHandler.bind(this);**
    }
render() {
        return (
            <div>
                <div>{this.state.message}</div>
                **<button onClick = {this.clickHandler}>Event</button>**
            </div>
        )
    }
clickHandler = () => {
        this.setState({
            message: 'Goodbye!'
        })
    }