[英]Call a React Component with an onClick event
I need to call a Component (ExampleComp), and when the button is clicked, call againthe component (ExampleComp).我需要调用一个组件(ExampleComp),当单击按钮时,再次调用该组件(ExampleComp)。 The idea is to call the Component(ExampleComp) as many times as you press the button.
这个想法是在您按下按钮时多次调用 Component(ExampleComp)。
function newComponent{
<ExampleComp/>
}
------
return(
<div>
<ExampleComp/>
<Button className="btnNew" onClick=
{newComponent}> Create a new Component</Button>
</div>
)
Actually i don't know how to do it exactly and i would apreciate your help.其实我不知道该怎么做,我会感谢你的帮助。
You can use the state for this purpose.为此,您可以使用 state。 Let's say your state is something like this:
假设您的 state 是这样的:
this.state = { items: [] };
You can render all the items like the following example:您可以渲染所有项目,如下例所示:
return (
<div>
{this.state.items.map(item => {
return <ExampleComp exampleProp={item.exampleProp} />;
})}
<Button className="btnNew" onClick={newComponent}>
Create a new Component
</Button>
</div>
);
And finally, you can push an item into the state, and React will take care of the rest.最后,您可以将一个项目推入 state,React 将处理 rest。
function newComponent{
newItem = { exampleProp: 'Something?' };
this.setState((state, props) => ({ items: [...items, newItem] }));
}
This will do the job.这将完成这项工作。 I just used "exampleProp" to be an example but you don't have to use it.
我只是使用“exampleProp”作为示例,但您不必使用它。 Actually, the state can be just a number too.
实际上,state 也可以只是一个数字。 The important part is using state in every user interface change .
重要的部分是在每个用户界面更改中使用 state 。
render(){
return (
<Button className="btnNew" onClick={ this.setState({ clicked:true }) }>Create a new Component</Button>
{
this.state.clicked ? {newComponent} : null
}
)
}
This would help but though not recommended by me as setState
will re-render(load) the component again onClick.这会有所帮助,但我不建议这样做,因为
setState
将再次重新渲染(加载)组件 onClick。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.