[英]Call a React Component with an onClick event
我需要調用一個組件(ExampleComp),當單擊按鈕時,再次調用該組件(ExampleComp)。 這個想法是在您按下按鈕時多次調用 Component(ExampleComp)。
function newComponent{
<ExampleComp/>
}
------
return(
<div>
<ExampleComp/>
<Button className="btnNew" onClick=
{newComponent}> Create a new Component</Button>
</div>
)
其實我不知道該怎么做,我會感謝你的幫助。
為此,您可以使用 state。 假設您的 state 是這樣的:
this.state = { items: [] };
您可以渲染所有項目,如下例所示:
return (
<div>
{this.state.items.map(item => {
return <ExampleComp exampleProp={item.exampleProp} />;
})}
<Button className="btnNew" onClick={newComponent}>
Create a new Component
</Button>
</div>
);
最后,您可以將一個項目推入 state,React 將處理 rest。
function newComponent{
newItem = { exampleProp: 'Something?' };
this.setState((state, props) => ({ items: [...items, newItem] }));
}
這將完成這項工作。 我只是使用“exampleProp”作為示例,但您不必使用它。 實際上,state 也可以只是一個數字。 重要的部分是在每個用戶界面更改中使用 state 。
render(){
return (
<Button className="btnNew" onClick={ this.setState({ clicked:true }) }>Create a new Component</Button>
{
this.state.clicked ? {newComponent} : null
}
)
}
這會有所幫助,但我不建議這樣做,因為setState
將再次重新渲染(加載)組件 onClick。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.