在阅读有关React的教程时,我注意到了以下代码。
componentDidMount () {
ref.on('value', function (snapshot) {
this.setState(function () {
return {
friends: snapshot.val()
}
})
}.bind(this)
}“ref.on”方法从何而来?这是被烘焙成反应的东西还是JavaScript函数?我在https://facebook.github.io/react/docs/react-api.html或https://developer.mozilla.org/en-US/docs/Web/JavaScript这里找不到它。此外,在反应组件中的另一个位置也有'ref.off‘。
componentWillUnmount () {
ref.off()
}编辑:
知道它可能是伪码是有帮助的。这是这门课的https://learn.tylermcginnis.com/courses/50507/lectures/762618。但你必须登录才能看到它。它在关于反应生命周期事件的章节中。
我问的是'.on‘和'.off’部分,而不是'ref‘。
发布于 2017-07-11 21:44:23
ref是对已安装组件的引用。使用ref,您将能够访问挂载组件的类方法。
class Foo extends Component {
render() {
return <span onClick={this.onDivClick}>hi</span>
}
onSpanClick = () => {
// do something
}
}
class Bar extends Component {
render() {
return <div onClick={this.onDivClick}>
<Foo ref={c => this.ref = c}/>
</div>
}
onDivClick = () => {
this.ref.onSpanClick() // reference to the mounted Foo instance and call the method onSpanClick
}
}发布于 2017-12-06 01:13:42
类似于jQuery的添加和删除事件侦听器的方法。可能只是举个例子。
https://stackoverflow.com/questions/45044545
复制相似问题