我正在尝试通过postMessage API与iframe通信,但ES6中的eventListeners管理出现问题
在文档中指出
使用React,每个方法都会自动绑定到其组件实例(使用ES6类语法时除外)
问题在于this.handler.bind(this) !== this.handler
所以当我完成事件后,由于无法保存对处理程序的引用,因此无法删除侦听器。 我可以尝试封装该函数,但是封装函数也需要绑定。 我也可以尝试替代构造函数,但是我不确定这是个好主意,而且我不知道它需要的参数。 我很确定我在这里错过了重点。
任何帮助将非常感激 !
export default class SomeComponent extends Component {
handleIframeData(event) {
// some stuff in there that will need 'this' to be set to the component's context, to get props for example.
}
componentDidMount() {
window.addEventListener('message', this.handleIframeData.bind(this), false)
}
componentWillUnmount() {
// won't work because 'this.handleIframeData.bind(this) !== this.handleIframeData'
window.removeEventListener('message', this.handleIframeData, false)
}
render() {
return (
<div className="SomeComponent" style={{height: '100%', width:'100%', display: 'table'}}>
<iframe src="assets/iframe/index.html" style={{display: 'table-row', width: '100%', height:'100%', border: 0}}></iframe>
</div>
)
}
}
不管怎么说,还是要谢谢你 !
问题跟踪器用于React的错误,而不是常规支持。 为此使用堆栈溢出或IRC。
话虽如此,该问题的通用解决方案是保留对绑定处理程序的引用。 例如,您可以在构造函数中绑定方法:
constructor(props) {
super(props);
this.handleIframeData = this.handleIframeData.bind(this);
}
另请参阅介绍类的博客文章: https :
@fkling这正是我要说的:P。 在所有方面都正确。 谢谢!
对此表示抱歉,再次感谢!
最有用的评论
问题跟踪器用于React的错误,而不是常规支持。 为此使用堆栈溢出或IRC。
话虽如此,该问题的通用解决方案是保留对绑定处理程序的引用。 例如,您可以在构造函数中绑定方法:
另请参阅介绍类的博客文章: https :