简体   繁体   English

如何从 React 中的父级访问子组件中的变量?

[英]How can I access variables in children components from parent in React?

I'm trying to learn React through building out a form/calculator type app.我正在尝试通过构建表单/计算器类型的应用程序来学习 React。 Im learning that React is unidirectional and I can't seem to find the way to work with this.我了解到 React 是单向的,我似乎找不到解决这个问题的方法。 I am trying to make a table that accepts input values about patients changing care, then calculates an acuity(difficulty) level and uses that number to total all acuity on the unit and decide how many staff are needed per shift.我正在尝试制作一个表格,该表格接受有关患者改变护理的输入值,然后计算敏锐度(难度)级别并使用该数字来总计该单位的所有敏锐度,并决定每个班次需要多少员工。

So, I used a component that builds each table row so that I could create random ages and random names from an api, and reduce repetitiveness.因此,我使用了一个组件来构建每个表格行,以便我可以从 api 创建随机年龄和随机名称,并减少重复性。 Then that component allows the user to choose changing levels of care.然后该组件允许用户选择不断变化的护理级别。 How can I get the acuity score from each row in Patient.js component back to the parent lvl so that I can use it to calculate the cumulative acuity level for all patients?如何将 Patient.js 组件中每一行的敏锐度分数返回给父级 lvl,以便我可以使用它来计算所有患者的累积敏锐度级别? I'm very confused when it comes to understanding states.在理解状态方面,我非常困惑。 Thanks!谢谢!

//----------------------Patient.js-------------------------
import React, { useState} from "react";
import FakePatient from "./PtNameGenerator";
import AgeNumber from "./AgeGenerator";

function Patient(props) {
    const [totalAcuity, setTotalAcuity] = useState(0);
    const [assistance, setAssistance ] =useState('');
    const [oriented, setOriented ] =useState('');
    const [incontinent, setIncontinent ] =useState('');
    const [intubated , setIntubated ] =useState('');

    var acuity = 0;

    if (assistance === 'ind') {
        acuity += 1;
    } else if (assistance === 'sba') {
        acuity += 2;
    } else if (assistance === '1pa') {
        acuity += 3;
    } else if (assistance === '2pa') {
        acuity += 4;
    } else {
        acuity = 0;
    }

    if (oriented === "4") {
        acuity += 1;
    } else if (oriented === '3') {
        acuity += 2;
    } else if (oriented === '2') {
        acuity += 3;
    } else if (oriented === '1') {
        acuity += 4;
    } else {
        acuity = 0;
    }

    if (incontinent === "y") {
        acuity += 2;
    } else if (assistance === 'n') {
        acuity += 1;
    } else {
        acuity = 0;
    }

    if (intubated === "y") {
        acuity += 4;
        
    } else if (intubated === 'n') {
        acuity += 1;
    } else {
        acuity = 0;
    };


    return <tr className="Patient-row">
        <td className="Room-number">
            {props.room}
        </td>
        <td>
            <FakePatient />
        </td>
        <td>
            <p><AgeNumber/></p>
        </td>
        <td>
            <select name="assistance" onChange={event => setAssistance(event.target.value) }>
                <option value="na">Select</option>
                <option value="ind">Ind</option>
                <option value="sba">SBA</option>
                <option value="1pa">1PA</option>
                <option value="2pa">2PA</option>
            </select>    
        </td>
        <td>
            <select name="oriented" onChange={event => setOriented(event.target.value) } >
                <option value="4">x4</option>
                <option value="3">x3</option>
                <option value="2">x2</option>
                <option value="1">x1</option>
            </select>    
        </td>
        <td>            
            <select name="incontinent" onChange={event => setIncontinent(event.target.value) }>
                <option value="n">N</option>
                <option value="y">Y</option>
            </select>   
        </td>
        <td>            
            <select name="intubated"  onChange={event => setIntubated(event.target.value) }>
                <option value="n">N</option>
                <option value="y">Y</option>
            </select>   
        </td>
        <td className="Acuity-Score">            
              <p className="AcuityScoreResult">
                { acuity }
            </p>
        </td>
    </tr>;
};

export default Patient;




//----------------------App.js-------------------------
import React, { useEffect, useState } from 'react'
import './css/style.css';
import './css/reset.css';
import logo from "./assets/logo.svg";
import Patient from './Components/Patient';




function App() {

  const [acuity, setacuity] = useState(0);
  const [nurse, setnurse] = useState(0);
  
  /*
  const arr = document.querySelectorAll('.AcuityScoreResult');
  Array.from(arr).forEach(el => {
      let acuityrow = parseInt(el.innerHTML);
      setacuity(prevacuity => prevacuity + acuityrow);
  });
  */
  //when generate clicked
  const renderScoreTotal = () => {
    console.log(nurse);
  }




  return (
    <div className="App">
      <main>
        <section className="Left_col Padding">
          <img className="Center" src={ logo } alt="" />
          <h3>Staffing Matrix</h3>
          <h2>My Units</h2>
          <hr />
          <ul>
            <li className="Active-unit">2N Med/Surg</li>
            <li>4N Behavioral Health</li>
            <li>Emergency Department</li>
            <li>8E Oncology</li>
            <li>7SW Neuro ICU</li>
            <li>8NW Neonatal ICU</li>
          </ul>
          <button className="Logout-btn">Log Out</button>
        </section>
        <section className="Upper_col Padding">
          <div className="Date-container">
            <div className="Day">Thursday,</div>
            <div className="Date">November 2nd 2021</div>
          </div>
          <div>
            <h2 className="Hospital-title">Sedona Medical Center</h2>
            <h3 className="Unit-title Active-unit">Medical Surgical Unit</h3>
          </div>
        </section>
        <section className="Content_container Padding">
          <table>
            <thead>
              <tr>
                <th>Room #</th>
                <th>Name</th>
                <th>Age</th>
                <th>Assistance</th>
                <th>Oriented</th>
                <th>Incontinent</th>
                <th>Intubated</th>
                <th>Acuity Score</th>
              </tr>
            </thead>
            <tbody>
              < Patient room={401} />
              < Patient room={402} />
              < Patient room={403} />
              < Patient room={404} />
              < Patient room={405} />
              < Patient room={406} />
              < Patient room={407} />
              < Patient room={408} />
              < Patient room={409} />
              < Patient room={410} />
              < Patient room={411} />
              < Patient room={412} />
              < Patient room={413} />
              < Patient room={414} />
              < Patient room={415} />
              < Patient room={416} />
            </tbody>
          </table>
          <button onClick={renderScoreTotal} className="Generate-btn">
            Generate
        </button>
          <section className="Staff-ratios">
            <div className="Staff-card">
              <p className="Staff-title">Nurse</p>
              <p className="Staff-number">{ nurse }</p>
            </div>
            <div className="Staff-card">
              <p className="Staff-title">CNA</p>
              <p className="Staff-number">3</p>
            </div>
            <div className="Staff-card">
              <p className="Staff-title">Social Work</p>
              <p className="Staff-number">2</p>
            </div>
            <div className="Staff-card">
              <p className="Staff-title">PT/OT</p>
              <p className="Staff-number">2</p>
            </div>
            <div className="Staff-card">
              <p className="Staff-title">EVS</p>
              <p className="Staff-number">2</p>
            </div>
            <div className="Staff-card">
              <p className="Staff-title">Provider</p>
              <p className="Staff-number">2</p>
            </div>
          </section>
        </section>
      </main>
    </div>
  );
}

export default App;


One way to do it is by using a value cache.一种方法是使用值缓存。 you can use something like redux to maintain a set of global variables (value cache) that you can access from anywhere.您可以使用redux 之类的东西来维护一组可以从任何地方访问的全局变量(值缓存)。 React will automatically re-render corresponding UI components when values change.当值发生变化时,React 会自动重新渲染相应的 UI 组件。

More info in their website - https://redux.js.org/introduction/getting-started更多信息在他们的网站 - https://redux.js.org/introduction/getting-started

However, if all your components are in one page, it's simpler to use useEffect react hook但是,如果您的所有组件都在一个页面中,则使用useEffect react hook 会更简单

More info in their website - https://reactjs.org/docs/hooks-reference.html#useeffect更多信息在他们的网站 - https://reactjs.org/docs/hooks-reference.html#useeffect

For these kinds of libraries, your mantra should be "props down, events up".对于这些类型的图书馆,你的口头禅应该是“道具向下,事件向上”。 You pass props to children and attach event listeners to the children in order for them to tell you that things have changed.您将道具传递给孩子并将事件侦听器附加到孩子,以便他们告诉您事情发生了变化。 The host (parent) component then decides what to do with the event data.主机(父)组件然后决定如何处理事件数据。 Perhaps an onAccuityChange listener that you pass to Patient that will be called when it changes.也许您传递给 Patient 的onAccuityChange侦听器将在它更改时调用。

Alternatively, calculate the value in the host and pass it to the child.或者,计算主机中的值并将其传递给子进程。

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

相关问题 如何从反应中的 class 组件访问上下文变量? - How can I get access to context variables from class components within react? 如何使用 React 中的 Hooks 在两个子组件中更改父 state? - How can I change parent state in two children components using Hooks in React? React 如何在子组件中管理来自父组件的道具 - React how to manage props from parent inside children components 如何访问 React Native Web 中引用的子组件? - How do I access children components of a reference in React Native Web? 我如何从道具访问我的反应组件中的历史记录? - how can i access the history in my react components from props? 如何让子组件可以访问 VueJs 中的父组件方法 - How to have children components have access to parent components method in VueJs 我可以在其父级的反应组件中设置子级道具吗? - Can I set the children props in a react component from its parent? 我如何使用父母身份证访问孩子 - How can i access children using parent id 在 React 中从多个子组件向一个父组件发送信息 - Send information from multiple children components to one parent component in React 如何动态添加父组件时,如何访问父组件的子组件值? - How can I access child components values from a parent component when they are added dynamically?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM