来解释情况。我有一个子组件,有一个雪佛龙旋转的点击。我需要实现从孩子到父母和祖父母的道具数据。
<ChildComponent>
<ParentComponent>
<GrandParentComponent>
在ChildComponent内部有箭头图标( img )
const [rotateIcon, setRotateIcon] = useState(false);
const expandAttachment = useCallback(() => {
setRotateIcon(!rotateIcon);
}, [rotateIcon]);
<img src="assets/arrow" transform={rotateIcon ? 'rotate(90deg)' : 'rotate(0)'} >
这是工作但是..。我需要支持GrandParentComponent公司的rotateIcon state。
不仅仅是孩子对父母。从孩子到父母,从父母到另一个层次。GrandParent。
我该怎么做?这是个好办法吗?我有什么选择?我不是在系统中使用redux,而是使用上下文!
说清楚了。所有三个组件都连接在一起。每个人都是一个孩子的父母!
发布于 2022-05-12 12:56:24
在我看来,你有三个选择:
然而,我确实使用和推荐使用redux这样的复杂操作。当您理解redux背后的想法时,就很容易使用它。
发布于 2022-05-12 13:03:17
将状态存储在GrandParentComponent
中,并在组件之间传递,作为到达ChildComponent
的支柱。道具应该从父组件传递到子组件。
发布于 2022-05-12 13:23:34
您可以执行支柱钻削,即向<GrandParentComponent/>
组件添加一个状态并将其作为支柱传递给子组件。
祖父母
export default GrandParentComponent(){
const [rotateIcon, setRotateIcon] = useState(false);
// pass the state and setState down to the children
return <ParentComponent rotateIcon={rotateIcon} setRotateIcon={setRotateIcon}/>
}
亲本
export default ParentComponent({rotateIcon, setRotateIcon}){
// pass props to child component again
return <ChildComponent rotateIcon={rotateIcon} setRotateIcon={setRotateIcon}/>
}
儿童
export default ChildComponent({rotateIcon, setRotateIcon}){
const expandAttachment = useCallback(() => {
setRotateIcon(!rotateIcon);
}, [rotateIcon]);
<img src="assets/arrow" transform={rotateIcon ? 'rotate(90deg)' : 'rotate(0)'} >
}
道具钻探本身并没有什么坏处,但随着复杂程度的增加,应用程序的状态管理变得越来越困难。
为了避免这种情况,我们要么使用,要么使用Redux。React上下文本身就是react本身,因此它非常轻量级,同时功能强大。这是适合你这种情况的最佳选择。
要简短地回答这个问题,请阅读如何实现React和useContext钩子这里。
https://stackoverflow.com/questions/72221897
复制