使用React.render()渲染的两个组件之间的交互是否可能

Is interation between two components rendered using React.render() possible?

本文关键字:之间 组件 交互 两个 是否 render React 使用      更新时间:2023-09-26

我在一个页面中有一个员工列表。每个员工项目旁边都有一个复选框。这是使用react js开发的。现在,每隔5秒,我需要根据员工的复选框状态,在页面上检查并显示一些可用/不可用的员工状态。

<div id="container"> <!-- List of employees will be placed here by react.js --> </div>

<div id="status-bar">

你能告诉我两个div是如何相互作用的吗?因为我正在分别渲染它们:

   React.render(<ListItems />, document.getElementById('container'));
   React.render(<StatusComponent />, document.getElementById('status-bar'));

我不相信这两个组件可以在不使用父组件的情况下相互交互。我建议制作一个将两者结合起来的组件,比如这样(用ES6编写,根本没有测试……只是举个例子):

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>
    )
  }
}

实际上,您需要做的是让EmployeeModule处理两个组件之间的交互。您可以从ListItems模块中获得所需的信息,并将其设置在父模块的状态上。在_countEmployees内部调用setState将触发对render函数的调用,该函数将在StatusComponent上设置属性numEmployees,从而更新您的状态模块。

希望这能帮助

我认为最好、更简单的方法是创建存储。您可以使用reduxJS轻松创建存储。您还可以将一个块包含在另一个块中,并通过this.ops提供数据。