javascript - 如何让 React 父组件在没有表单的情况下访问子状态(使用沙盒)?
问题描述
我目前正在寻找一种state
从父组件访问子组件的方法,该组件将处理整个页面的 API 调用。
实际问题如下:
Parent
是将渲染两个组件的父Child
组件。
每个Child
都有它负责的状态。
“Kind of Submit Button”将有一个“Kind of Submmit Action”(所有这些都被引用,因为这不是一个表单)并且应该触发该函数以提供对子状态的访问。有没有办法(一些 React 特性)在不使用<form>
或不创建中间父组件来保存所有状态的情况下做到这一点?我希望每个孩子都对自己的状态负责。
import React, { useState, useRef } from "react";
function ChildOne() {
const [childOneState, setChildOneState] = useState(false);
return (
<React.Fragment>
<h3>Child One</h3>
<p>My state is: {childOneState.toString()}</p>
<button onClick={() => setChildOneState(true)}>Change my state</button>
</React.Fragment>
);
}
function ChildTwo() {
const [childTwoState, setChildTwoState] = useState(false);
return (
<React.Fragment>
<h3>Child Two</h3>
<p>My state is: {childTwoState.toString()}</p>
<button onClick={() => setChildTwoState(true)}>Change my state</button>
</React.Fragment>
);
}
function Button(props) {
return (
<button onClick={props.kindOfSubmitAction}>Kind of Submit Button</button>
);
}
function Parent() {
const childOneState = useRef("i have no idea");
const childTwoState = useRef("ihave no idea");
function kindOfSubmitAction() {
console.log("This is the kindOfSubmit function!");
// This function would somehow get
// access to the children state and store them into the refs
return;
}
return (
<React.Fragment>
<h1>Iam Parent</h1>
<div>
<b>Child one state is: </b>
{childOneState.current}
</div>
<div>
<b>Child two state is: </b>
{childTwoState.current}{" "}
</div>
<Button kindOfSubmitAction={kindOfSubmitAction} />
<ChildOne />
<ChildTwo />
</React.Fragment>
);
}
export default Parent;
解决方案
当多个组件需要访问相同的数据时,就该提升状态了。
推荐阅读
- c# - 如何操作数据表中的值
- dart - 如何在 Dart 中将带逗号的字符串转换为双精度?
- python - 仅来自管理站点的配置文件更新
- python - 在 Jupyter Notebook 上编写代码时如何解决 Python3 中的 FileNotFound 错误?
- reactjs - 我们如何将其添加到我们的网站。React js 或任何网站,编辑器
- algorithm - 一个关于0和1序列的算法问题
- sql - 使用 oracle 11g,如何解决 nginx web 服务器中的 502 bad gateway 错误?
- android - 使用适用于 Android 的 Google 登录获取 Google API 访问令牌的首选方法是什么?
- react-native - 带有 Expo 的 Firebase 调试视图
- reactjs - 如何在 AWS 中部署 NEXT.JS (MERN)?