首页 > 解决方案 > 从子组件返回值到父组件 React

问题描述

所以我试图在我的一个类组件中使用一个反应计时器。我想出了如何连接它,但现在我需要将时间保存到父母的状态。我怎么能继续这样做?由于时间是在子组件上测量的。所以本质上我需要保存从子组件到父状态的时间。

标签: javascriptreactjs

解决方案


想到的短语是Lifting State up。React 有一个“自上而下”的数据流。所以你的状态需要在父组件中初始化并传递给需要它的子组件。例如(伪代码,可能不起作用)

function Parent() {
  const [text, setText] = useState('hello world')

  return (
    <>
      <Child text={text} />
      <OtherChild text={text} setText={setText} />
    </>
  )  
}

function Child({ text }) {
  return <p>{text}</p>
}

function OtherChild({ text, setText }) {
  return (
    <input
      onChange={e => setText(e.target.value)}
      value={text} />
  )
}

推荐阅读