javascript - 从子组件返回值到父组件 React
问题描述
所以我试图在我的一个类组件中使用一个反应计时器。我想出了如何连接它,但现在我需要将时间保存到父母的状态。我怎么能继续这样做?由于时间是在子组件上测量的。所以本质上我需要保存从子组件到父状态的时间。
解决方案
想到的短语是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} />
)
}
推荐阅读
- laravel - Laravel 图像响应头 access-control-allow-origin: * 设置问题
- python - 试图建立一个预测模型来处理缺失值和编码分类特征
- google-bigquery - Google Ads 的大查询数据传输
- python - 在 python jupyter 中导入模块问题
- laravel - 在laravel livewire中使用choice.js进行选择/多选不起作用
- ubuntu-20.04 - wps office 在 kso_qt::QSocketNotifier::type() 中因 SIGSEGV 崩溃
- zeal - 如何以热情或速度使用 mozila 开发者网络文档?
- xcode10 - 有什么方法可以使用 iOS 15 在高山脉上运行 xcode 10
- java - 在 android 11 中下载 pdf
- python - 如何在 python 环境中从我当前的所有模块创建 python 包?