ReactJS: Dynamically add a component on click(ReactJS:点击时动态添加组件)
问题描述
我有一个菜单按钮,按下时必须添加一个新组件.它似乎有效(如果我手动调用该函数来添加它们显示的组件).问题是,如果我单击按钮,它们不会显示出来,我想是因为我应该使用 setState 来重绘它们.我不确定如何在另一个函数/组件中调用另一个组件的 setState.
这是我的 index.js
然后我有 Menu.js
最后是 Block.js
我是 React 的初学者,所以我什至不确定我的方法是否正确.感谢您提供的任何帮助.
下面我敲了一个非常简单的父/子类型设置,..
Parent 负责渲染 Button,这里我只是使用了一个简单的编号数组.当您单击任何按钮时,它会调用 Parent 中的 setState,这反过来会导致 Parent 重新渲染它的 Children.
<块引用>注意:我也使用过 React Hooks 来做这件事,我只是找到了更多自然且更易于使用.可以使用Classes,原理相同适用.
I have a menu button that when pressed has to add a new component. It seems to work (if I manually call the function to add the components they are shown). The problem is that if I click the button they are not shown, and I suppose because I should use setState to redraw them. I am not sure how to call the setState of another component within another function/component.
This is my index.js
Then I have the Menu.js
And finally the Block.js
I am a React complete beginner so I'm not even sure my approach is correct. Thank you for any help you can provide.
Below I've knocked up a really simple Parent / Child type setup,..
The Parent is responsible for rendering the Buttons, I just used a simple numbered array here. When you click any of the buttons, it calls the setState in the Parent, and this in turns causes the Parent to re-render it's Children.
Note: I've also used React Hooks to do this, I just find them more natural and easier to use. You can use Classes, the same principle applies.
这篇关于ReactJS:点击时动态添加组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!