通知全局事件组件的最佳方式
Best way to notify a component of a global event
我有一个数据网格组件,用户可以在其中选择多行。组件管理当前选择的行作为其状态的一部分:
var Datagrid = React.createClass({
getInitialState() {
return {
selection: []
}
},
handleRowClick(id, event) {
if (event.ctrlKey) {
this.setState({ selection.concat([id]) });
}
},
render() {
return
<div>
{this.props.data.map( rowdata => <Row data={rowdata}> )}
</div>
;
}
});
ReactDOM.render(<Datagrid data={data}>, document.querySelector('#grid1'))
这很好地工作并封装了(实际上相当复杂的)选择逻辑。
但现在我希望这个组件在单击页面正文时取消选择所有行。
让全局存储管理所有数据网格的选择似乎相当麻烦,只是为了能够取消选择它们。我喜欢选择逻辑封装在组件中的事实,我只想通知它全局事件。
我曾想过将回调作为重置自身的道具来传递,但这似乎非常复杂:
var notification = false;
body.onclick = function () {
notification = function() { notification = false; } // Marks a pending notification
ReactDOM.render(<Datagrid data={data} notification={notification}>, document.querySelector('#grid1'))
}
var Datagrid = React.createClass({
...
render() {
if (this.props.notification) {
this.setState({ selection: [] });
this.props.notification(); // Reset the notification
}
...
}
});
ReactDOM.render(<Datagrid data={data} notification={notification}>, document.querySelector('#grid1'))
有更好的方法吗?
我认为处理这种情况的正确方法是在组件安装时设置侦听器,然后在组件卸载时将其删除,如下所示:
var Datagrid = React.createClass({
getInitialState() {
return {
selection: []
}
},
componentDidMount() {
document.body.addEventListener('click', this.handleClear);
},
componentWillUnmount() {
document.body.removeEventListener('click', this.handleClear);
},
handleClear() {
this.setState({ selection: []});
},
handleRowClick(id, event) {
if (event.ctrlKey) {
this.setState({ selection.concat([id]) });
}
},
render() {
return
<div>
{this.props.data.map( rowdata => <Row data={rowdata}> )}
</div>
;
}
});
相关文章:
- 在localhost Dev Box上测试JSONP请求的最佳方式
- 为react组件传递道具的最佳方式
- 让Webpack管理Quirky AMD定义的最佳方式
- 在承诺链中处理早期回报的最佳方式
- 在ng重复循环中显示条件内容的最佳方式是什么
- 在phonegap中为android调用onload函数的最佳方式
- 链接两个网页或网络应用程序的最佳方式
- 什么's是连接供应商js文件的最佳方式
- 什么's是在javascript中迭代项的最佳方式
- 在node.js中编写单元测试的最佳方式是什么
- 在页面上记录数据并实现pushstate()的最佳方式
- 使用AJAX在Rails中提交动态表单的最佳方式是什么
- 什么'这是加载jQuery的最佳方式
- 将大数组(字符串和类型数组的混合物)存储到blob或文件中/从blob或文件检索大数组的最佳方式
- 在网站上显示.mov作为加载屏幕的最佳方式
- 使用Angular存储用户以前是否选中过复选框,然后再调用它的最佳方式是什么
- 以角度渲染表中数据的最佳方式
- 删除集合中旧邮件/帖子的最佳方式
- 显示全屏Ajax加载程序的最佳方式
- PHP和JS中表单验证的最佳方式