简体   繁体   English

如何从 React JS 中的另一个组件更改同级组件的事件

[英]How to change sibling component on event from another component in React JS

I am new to ReactJS and doing some hands on practice.我是 ReactJS 的新手,并进行了一些实践。 I am working on a page where two tables are present and have linked data.我正在处理一个存在两个表并具有链接数据的页面。 I am looking for some suggestion around on how to communicate dependent data state to multiple elemnts in sibling component我正在寻找一些关于如何将依赖数据 state 传达给兄弟组件中的多个元素的建议

  1. Table 1 is professor table where each professor, subject and its availability is listed.表 1 是教授表,其中列出了每个教授、学科及其可用性。
  2. Table 2 is student table where each student is listed with subject and professor alloted.表 2 是学生表,其中列出了每个学生以及分配的学科和教授。

I've created tables for each as components and kept them under main component.我为每个组件创建了表,并将它们保存在主要组件下。

import React from 'react'
import Professor from '../Professor';
import Student from '../Student'

function Main() {
  return (
    <div className="w3-row-padding">
     <div className="w3-half"> <Professor /> </div>
     <div className="w3-half"> <Student /> </div>
   </div>
  );

}

Here is sample code for Professor component:这是教授组件的示例代码:

import teachers from "./teachers.json";
  class Professor extends Component{
  constructor(props) {
    super(props);
    this.state = {
    };
  }

 renderHeader = () => {
   let headerElement = ['name', 'present']

   return headerElement.map((key, index) => {
      return <th key={index}>{key}</th>
   })
 }

 renderBody = () => {
  return teachers && teachers.map(({ StaffID, StaffName, RoleID, Present }) => {
      return (
          <tr key={StaffID}>
              <td>{StaffName}</td>
              <td style={{verticalAlign: "middle"}}>
                <input type="checkbox" name={StaffName} defaultChecked={Present ? 'checked' : false} 
     />
              </td>
          </tr>
      )
  })
 }

 render() {
   return (
     <div>
       <table>
        <thead>
            <tr>{this.renderHeader()}</tr>
        </thead>
        <tbody>
            {this.renderBody()}
        </tbody>
    </table>
  </div>
  )
}

}

export default Professor;

Similarly I have another table for students listing data from student json containing student name and professor id.同样,我有另一个学生表,列出来自学生 json 的数据,其中包含学生姓名和教授 ID。

In professor table, user can mark presence of professor using checkbox.在教授表中,用户可以使用复选框标记教授的存在。 And on click of checkbox from Professors table, I want to update all rows in Student table with either alternate staff or a message.在从教授表中单击复选框时,我想用替代人员或消息更新学生表中的所有行。 In this case, I need to establish sibling component communication and update mulitiple rows in sibling table on an event.在这种情况下,我需要建立兄弟组件通信并在事件上更新兄弟表中的多行。 Any idea on how this can be achieved will be helpful.关于如何实现这一点的任何想法都会有所帮助。

Thanks谢谢

You need to lift up your state to the parent component您需要将 state 提升到父组件

import { useState } from "React"
import ...


function Main() {
 [teacherIsPresent, setTeacherIsPresent] = useState(false)

const toggleTeacherPresence = () => {
setTeacherIsPresent((previousState) => !previousState)
}

  return (
    <div className="w3-row-padding">
     <div className="w3-half"> <Professor toggleTeacherPresence={toggleTeacherPresence} teacherIsPresent={teacherIsPresent}/> </div>
     <div className="w3-half"> <Student /> </div>
   </div>
  );

}

in your child component:在您的子组件中:

        class Professor extends Component{
    
    // your code 
    <input type="checkbox" name={StaffName} defaultChecked={this.teacherIsPresent ? 'checked' : false} onChange{this.props.toggleTeacherPresence}
         />
// your other code
    }

You should consider to use functional components as Childs - since you do it in the parent anyways.您应该考虑将功能组件用作子组件 - 因为无论如何您都是在父组件中执行此操作。 This would make things easier...这会让事情变得更容易......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM