简体   繁体   中英

How to double and half a count in react?

I would like to be able to double and to half a number. How should I modify handleClick() method to do it?

I tried to modify count:

 count: prevState.count + 1

so it will be count: prevState.count + prevState.count or prevState.count * 2

but it didn't work.

 import React from "react" class App extends React.Component { constructor() { super() this.state = { count: 0 } this.handleClick = this.handleClick.bind(this) } handleClick() { this.setState(prevState => { return { count: prevState.count + 1 } }) } render() { return ( <div> <h1>{this.state.count}</h1> <button onClick={this.handleClick}>Change!</button> </div> ) } } export default App

这将不起作用,因为您将 0 加倍。所以 0*0=0

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM