Javascript 使用React.render()渲染两个组件之间的交互是否可能?
我在一页中有一个员工列表。每个员工项目旁边都有一个复选框。这是使用react js开发的。现在,每隔5秒钟,我需要根据员工的复选框状态在页面上检查并显示一些员工的可用/不可用状态Javascript 使用React.render()渲染两个组件之间的交互是否可能?,javascript,reactjs,Javascript,Reactjs,我在一页中有一个员工列表。每个员工项目旁边都有一个复选框。这是使用react js开发的。现在,每隔5秒钟,我需要根据员工的复选框状态在页面上检查并显示一些员工的可用/不可用状态 在我分别渲染这两个div时,您能否告诉我这两个div如何相互交互: React.render(<ListItems />, document.getElementById('container')); React.render(<StatusComponent />, do
在我分别渲染这两个div时,您能否告诉我这两个div如何相互交互:
React.render(<ListItems />, document.getElementById('container'));
React.render(<StatusComponent />, document.getElementById('status-bar'));
React.render(,document.getElementById('container');
React.render(,document.getElementById('status-bar');
我认为最好、更简单的方法是创建商店。您可以使用reduxJS轻松创建存储。您还可以将一个块包含在另一个块中,并通过这个.props提供数据。我不相信这两个组件可以在不使用父组件的情况下相互交互。我建议制作一个封装这两个组件的组件,类似这样的东西(用ES6编写,根本没有测试过……例如,只是突然出现):
类EmployeeModule扩展React.component{
_雇员人数(){
//在这里计算员工人数真是太神奇了。。
var count=getEmployeeCount();
this.setState({numEmployees:count});
}
componentDidMount(){
//每5秒盘点一次员工
this.interval=window.setInterval(()=>this._countEmployees(),5000));
}
组件将卸载(){
window.clearInterval(this.interval);
}
render(){
返回(
)
}
}
实际上,您需要做的是让EmployeeModule
处理这两个组件之间的交互。您可以从ListItems
模块中获取所需的信息,并将其设置为父模块的状态。在\u countEmployees
内部调用setState
将触发对render
函数的调用,该函数将在状态组件上设置属性numEmployees
,从而更新状态模块
希望这有帮助
React.render(<ListItems />, document.getElementById('container'));
React.render(<StatusComponent />, document.getElementById('status-bar'));
class EmployeeModule extends React.component {
_countEmployees() {
// Magic to get employee count here..
var count = getEmployeeCount();
this.setState({numEmployees: count});
}
componentDidMount() {
// Count employees every 5 seconds
this.interval = window.setInterval(() => this._countEmployees(), 5000));
}
componentWillUnmount() {
window.clearInterval(this.interval);
}
render() {
return (
<div className="employee-module-wrapper">
<ListItems />
<StatusComponent numEmployess="{this.state.numEmployees}" />
</div>
)
}
}