我对React还是很陌生,我有一个需求,我需要生成多个div,然后单击按钮以显示这些div。这是代码
export default class Test extends React.Component {
constructor() {
super();
this.state = {
dynaDiv: {}
};
this.onChangeFunc = this.onChangeFunc.bind(this);
this.buildDynamicDivs = this.buildDynamicDivs.bind(this);
}
onChangeFunc(inputName) {
const testId = "test"+(Math.floor(Math.random() * Math.floor(10)));
console.log(testId);
console.log(this.state.dynaDiv[testId].display);
this.setState((prevState) => {
console.log(prevState.dynaDiv[testId]);
return({
...prevState,
dynaDiv: {
...prevState.dynaDiv,
[testId]: {
...prevState.dynaDiv[testId],
display: prevState.dynaDiv[testId].display == "none"?"":"none"
}
}
});
});
}
buildDynamicDivs() {
let divs = [];
for(let i=0; i<10; i++) {
const dydiv = "test"+i;
this.state.dynaDiv[dydiv] = {display: "none"}
divs.push(<div key={i} id={dydiv} style={{display: this.state.dynaDiv[dydiv].display}}>Test div{i}</div>);
}
return divs;
}
render() {
return(
<div>
<button onClick={() => this.onChangeFunc("username")}>Toggle</button>
<button onClick={() => console.log("State: ", this.state)}>State</button>
{ this.buildDynamicDivs() }
</div>
);
}
}
因此,当用户单击Toggle时,应根据其先前状态(如果先前显示则隐藏其他显示)显示/隐藏1-9之间的随机生成数字。