Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/389.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 为什么一个函数需要绑定而另一个不需要';T_Javascript_Reactjs_Jsx - Fatal编程技术网

Javascript 为什么一个函数需要绑定而另一个不需要';T

Javascript 为什么一个函数需要绑定而另一个不需要';T,javascript,reactjs,jsx,Javascript,Reactjs,Jsx,我刚开始学习React和JavaScript。 在阅读教程时,我看到了一个组件的示例代码,它创建了一个切换按钮: class Toggle extends React.Component { constructor(props) { super(props); this.state = {isToggleOn: true}; this.handleClick = this.handleClick.bind(this); }

我刚开始学习React和JavaScript。
在阅读教程时,我看到了一个组件的示例代码,它创建了一个切换按钮:

class Toggle extends React.Component {
    constructor(props) {
        super(props);
        this.state = {isToggleOn: true};
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        this.setState(prevState => ({
            isToggleOn: !prevState.isToggleOn
        }));
    }

    render() {
        return (
            <button onClick={this.handleClick}>
                {this.state.isToggleOn ? 'ON' : 'OFF'}
            </button>
        );
    }
}
类切换扩展了React.Component{
建造师(道具){
超级(道具);
this.state={istogleon:true};
this.handleClick=this.handleClick.bind(this);
}
handleClick(){
this.setState(prevState=>({
isToggleOn:!prevState.isToggleOn
}));
}
render(){
返回(
{this.state.isToggleOn?'ON':'OFF'}
);
}
}
在我看来,
handleClick
render
函数都使用了类的
这个
对象,这超出了它们的范围(对吧?)


那么为什么我只需要将它绑定到
handleClick

Javascript在调用时分配作用域,而不是在定义时分配作用域。您需要将
bind()
您的
handleClick()
方法绑定到类,这样当从模板调用它时,它仍然可以通过
this
访问类的作用域

React模板被编译成javascript函数,因此如果您没有
bind()
您的
onClick={this.handleClick}
处理程序的作用域将是调用它的模板函数。在您的情况下,它将引用单击的按钮


如果您的事件处理程序从未引用过
this
,则不需要绑定,但由于您正在调用
this.setState()
,因此绑定是必要的,以使处理程序了解类的作用域。

在任何react类中,componentWillMount、componentDidMount、,渲染元素时,react在内部调用render etc,我们从不调用这些方法

现在,由于作用域是在调用时确定的,所以react的工作就是用适当的作用域调用/绑定这些方法

然而,上面示例中的其他函数(如handleClick)是我们制作的方法,react对此一无所知。此外,此方法的调用由我们定义(即单击按钮时)。因此,我们的工作就是调用/绑定具有正确作用域的此方法


这就是为什么在上面的例子中我们只绑定handleClick而不渲染函数。

我从未使用过react,但我猜
onClick
函数调用会用
窗口
对象或类似的东西替换
this
关键字。这实际上是使用默认的
addEventListener
方法发生的,该方法使用
This
=
窗口调用回调。可能是因为
handclick
是由
窗口调用的,因此必须绑定
this
关键字,这样它就不会被
窗口或调用click函数的人过度写入。我相信,否则,
this
将引用触发事件的按钮。@sweaver2112谢谢,我更新了我的答案,让它更清楚。难道不是
render()
调用它的模板函数,而不是按钮吗?并且
render()
在同一个类中,所以它应该共享相同的
这个