import React, {useState} from 'react' export default function Counter({initialCount}) { const [count, setCount] = useState(initialCount) return ( <div> <button onClick = {() => setCount(prevCount => prevCount - 1)}>-</button> <span>{count}</span> <button onClick = {() => setCount(prevCount => prevCount + 1)}>+</button> </div> ) }
same thing using Component
import React, { Component } from 'react' export default class Counter extends Component { constructor(props){ super(props); this.state = { count: props.initialCount } } render() { return ( <div> <button onClick={() => this.changeCount(-1)}>-</button> <span>{this.state.count}</span> <button onClick={() => this.changeCount(1)}>+</button> </div> ) } changeCount(amount) { this.setState(prevState => {return { count: prevState.count + amount}}) } }
No comments:
Post a Comment