2 回答

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超22個(gè)贊
你應(yīng)該在這里實(shí)現(xiàn) React State。您將添加的組件列表保存到 this.state。這是我的建議。
這是 App.js
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
clicked: false,
mycomponentlist:[]
};
this.my_func = this.my_func.bind(this);
}
my_func(){
let {mycomponentlist} = this.state;
var prop1 = prompt("Input here ");
var prop2 = "new_id";
mycomponentlist.push({prop1,prop2});
this.setState({mycomponentlist,clicked:true});
}
render() {
const {clicked,mycomponentlist} = this.state;
return (
<div id="app-root">
<button onClick={this.my_func }>Add</button>
{clicked&& mycomponentlist.map(mycomponent=> <MyComponent p1={ mycomponent.prop1 } p2={ mycomponent.prop2 }/>)}
</div>
);
}
}
export default App;
這是 MyComponent.js
import React, { Component } from 'react';
class MyComponent extends Component {
render() {
const { p1,p2} = this.props;
return (
<div >
//you can use p1,p2 here...
<p>{p1}</p>
<p>{p2}</p>
</div>
)
}
}
export default MyComponent;
我相信這會奏效。當(dāng)?shù)谝淮吸c(diǎn)擊按鈕然后點(diǎn)擊狀態(tài)變?yōu)檎鏁r(shí),組件數(shù)組會在每次渲染時(shí)顯示。

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
嘗試這樣的事情,可能需要根據(jù)您的具體要求稍微修改一下。
import React,{useState} from 'react';
const App = ()=> {
const [items, setItems] = useState([]);
return(
Your JSX
{items.map((item)=> {
return(
<li>item</li>
);
})
<button onClick={push into items}
);
}
添加回答
舉報(bào)