I created a React component, and when the "New Section" button is clicked, the component will show up. The problem I am having right now is I want it to be for example, if the button was clicked three times, there will be three sections showing up. But now, when I clicked the "New Section" button, there is a new section showing up and it is in the right place, but I am not able to click it again, and display more sections.
You're very close!
You could have a theoretically infinite number of sections so a boolean (true/false) won't cut it for showing more sections. What you need to do is switch that to an integer (1, 2, 3, etc.)
So at the start, you will only have 1 section (I'm assuming) so your state should be this.state = {sections: 1}
Change your button to setState({sections: this.state.sections+1})
so when the new button is clicked, it will add to your sections variable.
And now to get your sections to show properly, you'll want to remove the hardcoded <Section />
and replace it with a for loop.
for (var i=0; i < this.state.sections; i++) {
<Section />
}
If that does it for you then that's that, but if you want to take this a step further and store the values for each section within the sections variable, you'll have to use sections as an array.
this.state = {sections: [{your_attributes_here: your_values_here}]}
So anytime the button is clicked, it will have to instead now push to the array a new sections object. This can be achieved simply as
let sections = this.state.sections.push({section_info_here});
this.setState({sections: this.state.sections.push({section_info_here})});
and generating the html for the sections will now be
{this.state.sections.map((section, i) => {
return <Section sectionData={section}/>
})}
This method is only if you need to store data for each individual section. Either method will get you past the problem of not being able to add more than 1 section. Hope this helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.