在直接的 jQuery 中,我可以做类似的事情
$('#myCollapsible').on('click', 'hidden.bs.collapse', function () {
// do something…
})
但是在 React 中有一个“正确”的方法吗?如果上述是要走的路,我应该将该事件处理程序放在哪里?请注意,我没有使用react-bootstrap插件。
请您参考如下方法:
处理 React 不直接支持的事件的正确方法是在组件安装后向 DOM 节点添加事件监听器,并在组件卸载时将其删除:
class MyCollapsible extends React.Component {
constructor() {
super()
// Bind the method in the constructor instead of binding it in render, so you only do it once
this.handleHiddenBsCollapse = this.handleHiddenBsCollapse.bind(this)
}
componentDidMount() {
this.myCollapsible.addEventListener('hidden.bs.collapse', this.handleHiddenBsCollapse)
}
componentWillUnmount() {
this.myCollapsible.removeEventListener('hidden.bs.collapse', this.handleHiddenBsCollapse)
}
handleHiddenBsCollapse(event) {
// Do something...
}
render() {
// Settings refs with node => this.bla = node is recommended
// because this.refs is deprecated.
// in this example "node" is the DOM node itself, not a react reference
return (
<div ref={node => (this.myCollapsible = node)} />
)
}
}
使用 DOM 引用的文档:https://facebook.github.io/react/docs/refs-and-the-dom.html






