reactjs - 在 React JS 中从父组件更改子状态
问题描述
我有一些关于我的问题的文章,我知道如果我想从父组件更改子组件的状态,我必须提升父组件中的状态,但我不想这样做。
我有 2 个组件:
const Parent = () => {
const changeChild = () => {
}
return (
<button onClick={changeChild}>change state</button>
<Children/>
)
}
const Children = () => {
const [state, setState] = useState(false); //this state should be changed by parent to TRUE
}
问题:如何使用父组件将状态更改true
为位于子组件中的状态?changeChild
谁能帮忙?
解决方案
您可以尝试另一种方法。使用 useRef、forwardRef 和 useImperativeHandle 检查此代码段。
父.js
import { useRef } from "react";
import { Child } from "./Child";
export default function () {
const ref = useRef();
return (
<div>
<button onClick={() => ref.current.setState()}>
Click me to toggle the value in child
</button>
<Child ref={ref} />
</div>
);
}
Child.js
import { forwardRef, useState, useImperativeHandle } from "react";
export const Child = forwardRef(function (props, ref) {
//this state should be changed by parent to TRUE
const [state, setState] = useState(false);
function changeValue() {
return function () {
setState(!state);
};
}
useImperativeHandle(ref, () => ({
setState: () => changeValue()()
}));
return (
<div>
<b>changed value from parent</b> :{" "}
{state ? "Parent triggered to true" : "Parent triggered to false"}
</div>
);
});
注意:这不是推荐的,尝试使用提升状态。这只是为了理解目的,这是一种反模式
工作代码框
推荐阅读
- glsl - 处理透视阴影贴图深度值的非线性
- ada - 如何证明这个不变量?
- python - 熊猫如何复制具有不均匀列的数据框中的行,仅在特定列中存在数据并形成具有偶数列的新数据框?
- c++ - 如何访问作为我关注类的祖父母的基类成员?
- image - 在特征向量中应用 PCA 后,我们在数组中得到值错误。我该如何解决这个问题?
- python - 是否可以将 Tensorflow 2 模型与 Tensorflow 1 一起使用?
- reactjs - 从表中删除主题后,数据不会重新呈现
- iframe - 谷歌忽略索引外部嵌入式 iframe 结构化数据
- reactjs - 与其他图像叠加后如何保存图像?
- sql - 查询 date_time 字段的日期部分。yyyy-mm-dd