反应更新儿童道具
我的目标是:单击子组件中的一个按钮,然后删除该组件。
新的反应。在我的app.js中,我在该组件中有一个组件和道具:
<IntroSteps isHidden={false} />
在&lt; lt; gt;
组件中,我有逻辑来聆听ishidden> Ishidden
prop
export default function IntroSteps({isHidden}) {
if(isHidden) {
return null
}
return ( <div> content </div> )
}
我的目标是我的目标是我的目标是能够在Introsteps组件中更新ISHIDD。我尝试了以下操作,没有运气。正确的方法是什么?
const removeIntroSteps = () => {
isHidden = true
};
My goal: Click a button in a child component and have that component removed.
New to React. In my app.js I have a component and a prop within that component:
<IntroSteps isHidden={false} />
In the <IntroSteps>
component I have logic to listen for the isHidden
Prop
export default function IntroSteps({isHidden}) {
if(isHidden) {
return null
}
return ( <div> content </div> )
}
My goal is to be able to update isHidden within the IntroSteps component. I've attempted the following with no luck. What is the correct way to do this?
const removeIntroSteps = () => {
isHidden = true
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在评论中,您已经澄清了:
的最佳方法是让子组件调用父母通过它通过它的函数,并让父母要么让父母渲染子(而不是隐藏)或不渲染它(隐藏)(或者,或者,使用
isHidden
flag渲染它,并且儿童组件可以返回null
当isHidden
是是的,但这似乎是圆形的)。快速示例:
当您 can 将状态添加到子组件中,该状态可以使其维护单独的标志(例如,
hiddenmyself
例如,然后返回null
如果>
Ishidden 或hiddenmyself
是正确的),您无法直接更改Ishidden
prop的状态。这是父部件控制的东西,而不是孩子。In a comment you've clarified:
The best way to do that is to have the child component call a function that the parent passes it, and have the parent either render the child (not hidden) or not render it (hidden) (or alternatively, render it with the
isHidden
flag and the child component can returnnull
whenisHidden
is true, but that seems round-about).Quick example:
While you can add state to the child component that lets it maintain a separate flag (
hiddenMyself
for instance, then returnnull
if eitherisHidden
orhiddenMyself
is true), you can't directly change the state of theisHidden
prop. That's something the parent component controls, not the child.道具是不可变的,所以恐怕您可能无法在子女组件中更改它。我宁愿这样做:
在app.js中,
然后在子组件中,
只需在需要的任何地方调用
updateHidden
。Props are immutable So I'm afraid you might not be able to change it in the child component. I'd rather do it this way:
In app.js
Then in the child component,
simply call
updateHidden
wherever required.props props props of-ofly 不能。
您需要将功能传递给负责更新ISHIND状态的组件。
在内部的内存中,您需要添加此信息:
然后,在组件中:
Props are read-only, so you can't.
You need to pass a function to your component which is responsible for updating the state of isHidden.
In the IntroSteps, you need to add this for example:
Then, in your component:
为此,您需要将2个道具传递到Introsteps组件中。
当然,这两个变量可以通过
usestate
在父组件中定义。代码示例:
To do this, you need to pass 2 props into IntroSteps component.
Of course, these 2 variables could be defined in parent component by
useState
.Code example: