In my class component wanted change Initial State to True but don't want change to false after true, just change to the true, how can I changed setState? Thanks for help.
class Cardlist extends Component {
state = {
setopen : false
}
setOpen = () => this.setState(prevState => ({
setopen : !prevState.setopen // I don't know how can changed setState to always true
}))
render() {
const { products } = this.props;
return (
<div>
<button onClick={() => this.setOpen(true)} className="font-medium">
Basket
</button>
{(this.state.setopen) ? <Card {...products} open={this.state.setopen} /> : ''}
</div>
)
}
}
CodePudding user response:
Always keep the state in the setOpen to true.
setOpen = () => this.setState(prevState => ({setopen : true})
...
<div>
<button onClick={this.setOpen} className="font-medium">
Basket
</button>
</div>
Make state according to the argument passed
setOpen = (newVal) => this.setState({setopen : newVal})
...
<div>
<button onClick={() => this.setOpen(true)} className="font-medium">
Basket
</button>
<button onClick={() => this.setOpen(false)} className="font-medium">
Basket
</button>
</div>