Javascript 为什么将回调绑定到null工作?
可以在下面的链接中找到一个工作的WebPackageBin 我有两个部分。父组件通过prop将函数传递给其子组件,子组件的事件处理程序通过Javascript 为什么将回调绑定到null工作?,javascript,reactjs,Javascript,Reactjs,可以在下面的链接中找到一个工作的WebPackageBin 我有两个部分。父组件通过prop将函数传递给其子组件,子组件的事件处理程序通过func.bind(null,num)调用传入的函数以提供额外的预设参数 为什么dummyFunc.bind(null,666)有效,不应该bind使新创建的函数这个上下文变成null?因此,每个this.setState都应该是未定义的 父组件代码 import React from 'react' import Component from './Co
func.bind(null,num)
调用传入的函数以提供额外的预设参数
为什么dummyFunc.bind(null,666)
有效,不应该bind
使新创建的函数这个上下文变成null
?因此,每个this.setState
都应该是未定义的
父组件代码
import React from 'react'
import Component from './Component'
export default class Hello extends React.Component {
constructor(props) {
super(props)
this.state = {
foo: 2
}
this.foo = this.foo.bind(this)
}
foo(newValue) {
this.setState({
foo: newValue + this.state.foo
})
console.log(this.state.foo)
}
render() {
return (
<div>
<h1>App</h1>
<Component dummyFunc={this.foo} />
</div>
)
}
}
import React from 'react'
const Component = ({dummyFunc}) => {
return (
<div>
<button onClick={dummyFunc.bind(null, 666)}>BUTTON</button>
</div>
)
}
export default Component
从“React”导入React
从“./Component”导入组件
导出默认类Hello.Component{
建造师(道具){
超级(道具)
此.state={
傅:2
}
this.foo=this.foo.bind(this)
}
foo(新价值){
这是我的国家({
foo:newValue+this.state.foo
})
console.log(this.state.foo)
}
render(){
返回(
应用程序
)
}
}
子组件代码
import React from 'react'
import Component from './Component'
export default class Hello extends React.Component {
constructor(props) {
super(props)
this.state = {
foo: 2
}
this.foo = this.foo.bind(this)
}
foo(newValue) {
this.setState({
foo: newValue + this.state.foo
})
console.log(this.state.foo)
}
render() {
return (
<div>
<h1>App</h1>
<Component dummyFunc={this.foo} />
</div>
)
}
}
import React from 'react'
const Component = ({dummyFunc}) => {
return (
<div>
<button onClick={dummyFunc.bind(null, 666)}>BUTTON</button>
</div>
)
}
export default Component
从“React”导入React
常量组件=({dummyFunc})=>{
返回(
按钮
)
}
导出默认组件
为什么alert.bind(null,666)有效,bind不应该使这个上下文中新创建的函数变为null
它仅更改要绑定到的函数的上下文:警报
(并且仅适用于新创建的绑定函数)。因此,在alert
函数中,上下文将被更改,这几乎没有问题,因为内部alert
不会使用默认上下文,但这并不受约束
该代码的目的是部分应用alert
函数的参数,即数字666
从这个角度来看,使用匿名函数在语义上更为正确:
<button onClick={() => alert(666)}>BUTTON</button>
因此,您已经显式地绑定了上下文。在您这样做之后,每隔一次.bind()
都不会再更改上下文(这是按照标准的)。您的666非常666,所以我给您双击666this.foo=this.foo.bind(this)
清楚地将它绑定到其他上下文。通过执行dummyFunc.bind(null)
可以重新绑定它吗?不,显然不可以,因为这样代码就不起作用了。谢谢你解决了我的问题。我确实理解你最后的代码示例,这对我来说很有意义。然而,第一部分我不太清楚。我更新了我的问题(见问题末尾的代码块)。@LiXinyang不,它不应该是等价的:浏览器的警报
功能与react没有任何联系,它的设置状态
。这是一个显示弹出消息的函数,仅此而已。我不应该将警报
用作函数占位符。请看我的update@LiXinyang请参阅更新的答案。