本文介绍了子、父、祖父和曾祖父 React 组件中的递归计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个主要组件 ParentA,它的子组件为 ChildA、ChildB、ChildC 和 ParentB 和自身内部相同的重复组件.那么我实际上需要什么,如果我在 ChildF 中进行任何计算,这会立即反映在 ParentC 中的 A 列中,但它也应该立即反映在 ParentB 和 ParentA 列的 A.
期待回复.
解决方案
这里通常的解决方案是 提升状态,在本例中为ParentC
,并让ParentC
为后代组件提供更新ParentC
的方法的状态,通过 props 或 context 传递一个 setter.
这是一个使用 props 的小例子:
const {useState} = React;函数 ParentC() {const [计数器,setCounter] = useState(0);const addOne = () =>{setCounter(c => c + 1);};const addTwo = () =>{setCounter(c => c + 2);};返回 (<div><DisplayChild value={counter}/><UpdaterChild onAdd={addOne} label="添加一个"/><UpdaterChild onAdd={addTwo} label="添加两个"/>
);}function UpdaterChild({onAdd, label}) {返回 (<input type="button" value={label} onClick={onAdd}/>);}函数 DisplayChild({value}) {返回<div>值={值}</div>;}ReactDOM.render(, document.getElementById("root"));
<div id="root"></div><script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
注意 counter
如何在父级保存并传递给子级,以及(如果相关)适当的 setter 供他们调用.
I have a main component ParentA Which has children as ChildA, ChildB, ChildC and ParentB And same repeating components inside itself.So what actually i need, If I made any calculation inside ChildF This is instantly reflecting in ParentC In Column A, But it also should be Reflecting instantly in ParentB and ParentA column's A.
Looking forward for response.
解决方案
The usual solution here is to lift state up, in this case to ParentC
, and have ParentC
provide the descendant components a way to update ParentC
's state, by passing down a setter via props or context.
Here's a small example using props:
const {useState} = React;
function ParentC() {
const [counter, setCounter] = useState(0);
const addOne = () => {
setCounter(c => c + 1);
};
const addTwo = () => {
setCounter(c => c + 2);
};
return (
<div>
<DisplayChild value={counter} />
<UpdaterChild onAdd={addOne} label="Add One" />
<UpdaterChild onAdd={addTwo} label="Add Two" />
</div>
);
}
function UpdaterChild({onAdd, label}) {
return (
<input type="button" value={label} onClick={onAdd} />
);
}
function DisplayChild({value}) {
return <div>Value = {value}</div>;
}
ReactDOM.render(<ParentC/>, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
Notice how counter
is held at the parent level and passed down to the children, along with (where relevant) appropriate setters for them to call.
这篇关于子、父、祖父和曾祖父 React 组件中的递归计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!