【问题标题】:How can I read a variable from another component in React?如何从 React 的另一个组件中读取变量?
【发布时间】:2021-01-06 08:03:41
【问题描述】:

我使用 React 从组件中的两个选项元素接收这两个值。 问题:如何从另一个组件中读取这两个变量?

const handleInputChange = (e) => {   
    const valueFilterActive = document.getElementById("activeFilter").value;
    const valueFilterName = document.getElementById("bussFilter").value;
    alert(valueFilterName+valueFilterActive);   
 };

第二个组件代码行:

 return (
    <> 
      <div className="col-md-4 p-2">
        <FirstComponent/>
  
      </div>
      <div className="col-md-8 p-1 ">
          <div className={ valueFilterActive  === 'Activado' ? "text-success" : "text-primary card mb-1"} key={link.id}>

非常感谢!!!

【问题讨论】:

  • 第二个组件是否包含在第一个组件中?能否提供完整的组件代码?
  • 相反:第一个组件包含在第二个组件中。我只是添加更多代码以了解我需要什么。谢谢 M. Faisal

标签: reactjs react-hooks react-component react-context


【解决方案1】:

如果您想从另一个组件中读取变量,您可以使用多种方法。这取决于您如何链接这些组件。

如果基值在父级中并且您想将其传递给子级,请使用道具https://reactjs.org/docs/components-and-props.html

const element = <Welcome data1 ={valueFilterActive} data2 ={valueFilterName} />;

function Welcome(props) {  
return <h1>Hello, {props.valueFilterName} {props.valueFilterActive}</h1>;
}

如果基值在子级中,并且您想将其传递给父级,则使用回调函数 https://reactjs.org/docs/faq-functions.html

但如果它的方式更复杂,我建议使用 Context Hook https://reactjs.org/docs/hooks-reference.html#usecontext

(PS:同样在反应中你不使用getElementById,而是另一个名为useRef的钩子 https://reactjs.org/docs/hooks-reference.html#useref)

【讨论】:

    【解决方案2】:
    // in the component that renders <FirstComponent> create  hooks for values you'd like to track
    import React, { useState } from 'react';
    
    const [inputValues, setInputValues] = useState({});
    
    return (
      <> 
        <div className="col-md-4 p-2">
          <FirstComponent onChange={setInputValues}/>
    
        </div>
        <div className="col-md-8 p-1 ">
            <div className={ valueFilterActive  === 'Activado' ? "text-success" : "text-primary card mb-1"} key={link.id}>
    
    
    // in your <FirstComponent> call setInputValues and set variables 
    const handleInputChange = (e) => {   
      const valueFilterActive = document.getElementById("activeFilter").value;
      const valueFilterName = document.getElementById("bussFilter").value;
      // this will set `inputValues` variable to be an object with `valueFilterActive` and `valueFilterName` properties
      setInputValues({valueFilterActive, valueFilterName})
      alert(valueFilterName+valueFilterActive);   
    };
    

    【讨论】:

      猜你喜欢
      • 2012-07-22
      • 2019-05-10
      • 2021-08-15
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-29
      相关资源
      最近更新 更多