CODESANDBOX I want to generate checkboxes dynamically It works perfectly fine if I just simply call the function onclick. My problem is if I call it somewhere outside onclick or in another function and then call the function it simply doesn't get called.
This is my function to add the checkbox the other two functions are for the toggle and render.
function addCheckbox(name) {
const { checkboxes } = this.state,
label = name;
checkboxes.push({
checked: true,
label
});
this.setState({
checkboxes
});
}
function toggleCheckbox(index) {
const { checkboxes } = this.state;
checkboxes[index].checked = !checkboxes[index].checked;
this.setState({
checkboxes
});
}
function renderCheckboxes() {
const { checkboxes } = this.state;
return checkboxes
.map((checkbox, index) =>
<div>
<label>
<input
type="checkbox"
checked={checkbox.checked}
onChange={toggleCheckbox.bind(this, index)}
/>
{checkbox.label}
</label>
</div>
);
}
This is part of my render function:
</div>
{renderCheckboxes.call(this)}
<input ref="label" type="text" />
<button onClick={addCheckbox.bind(this,"krass")}>Add Checkbox</button>
Now when I call the addCheckbox function in another function it doesn't get called. Like this:
generatecheckbox()//Outside of render
{
addCheckbox.bind(this,"krass")
}
If I now change the OnClick to:
<button onClick={this.generatecheckbox()}>Add Checkbox</button>
It doesn't work. How do I fix this? CodeSandboxLink for reference: Link:
Aucun commentaire:
Enregistrer un commentaire