When someone clicks on "Add more" button, I want the pickers
variable to change (contain two instances of mainPart
.
On page load, there is only one mainPart
inside pickers
. But I want to change it when someone clicks on "Add more".
I have a react code like this:
export default class TestComponent extends React.Component {
constructor(props) {
// Stuff here
}
mainPart(a,b,c) {
return (
// Stuff here
)
}
changeMyVariable(a,b,c,type) {
if (type==1) {
return [
(
<span>
mainPart(a,b,c)
</span>
)
]
}
if (type==2) {
return [
(
<span>
mainPart(a,b,c)
</span>
),
(
<span>
mainPart(a,b,c)
</span>
)
]
}
}
render() {
let pickers = this.changeMyVariable(a, b, c,1);
return (
{pickers}
<button onClick={this.changeMyVariable(a, b, c,2)} type="button">Add more</button>
);
}
}
Firstly You need to use state to make your component render when type changes
constructor(props){
super(props)
this.state = {
type: 1
}
}
render(){
let pickers = this.changeMyVariable(a, b, c, this.state.type);
return (<>{pickers}
<button onClick={() => this.setState({type: 2})} /></>
);
}
Secondly You didn't handle button click event very well before. Your function would run immediately after render not on button click.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments