【问题标题】:How do I share the value of a variable to another component in react?如何在反应中将变量的值共享给另一个组件?
【发布时间】:2021-06-18 12:26:51
【问题描述】:

如何将变量传递给不同的组件?我在VariableWithData 组件中有一个钩子,当单击按钮时它会增加状态。如何将变量multiplied 的数据传输到组件NeedVariableData 上,以便在<h1> 标签上显示值?

//src/app.js

export const app = () => {
  return (
    <div>
      <VariableWithData />
      <NeedVariableData />
    </div>
  )
}

// src/components/VariableWithData.js

import { useState } from "react"

export const VariableWithData = () => {
  const [state, setState] = useState(2)

  function multiplyData(){
    const multiplied = state * 2;
  }
  return (
    <div>
      <input type="submit" onClick={multiplyData}/>
    </div>
  )
}

// src/components/NeedVariableData.js

export const NeedVariableData = () => {
  return (
    <div>
      <h1>{multiplyData}</h1>
    </div>
  )
}

【问题讨论】:

  • 嗨 Jeronimoo,如果组件处于父子关系中,您可以使用 Props。或者,如果您想跨组件共享数据,那么您可以使用 contextproviders 或者您可以使用 State
  • 你能告诉我在这个例子中是怎么做的吗? @HimanshuSaxena
  • 嗨@Jeronimoo33,我可以看到您已接受以下答案,希望您得到答案。如果需要更多信息,请告诉我们。谢谢。

标签: html reactjs properties react-hooks jsx


【解决方案1】:

你需要lift the state up.

import { useState } from "react"

export const App = () => {
  const [count, setCount] = useState(2);

  const handleClick = {
    setCount(c => c * 2);
  }

  return (
    <div>
      <VariableWithData onClick={handleClick} />
      <NeedVariableData multiplyData={count} />
    </div>
  )
}

// src/components/VariableWithData.js

export const VariableWithData = ({ onClick }) => {
  return (
    <div>
      <button onClick={onClick}/>
    </div>
  )
}

// src/components/NeedVariableData.js

export const NeedVariableData = ({ multiplyData }) => {
  return (
    <div>
      <h1>{multiplyData}</h1>
    </div>
  )
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-16
    • 2021-04-23
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    相关资源
    最近更新 更多