import React from 'react'
import { useState } from 'react'
export default function Count() {
const [count, setCount] = useState<number>(0)
const [value, setValue] = useState<number>(0)
const increment = () => {
setCount(count + value * 1)
}
const decrement = () => {
setCount(count - value * 1)
}
// 奇数再加
const incrementIfOdd = () => {
if (count % 2 !== 0) {
setCount(count + value * 1)
}
}
// 异步加
const incrementAsync = () => {
setTimeout(() => {
setCount(count + value * 1)
}, 1000)
}
const select = (e: any) => {
const index = e.target.selectedIndex // 选中项的index
setValue(e.target.options[index].value) // 选中项的value值
}
return (
<div>
<h1>当前求和为: {count}</h1>
<select onChange={select}>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<button onClick={incrementIfOdd}>当前求和为奇数再加</button>
<button onClick={incrementAsync}>异步加</button>
</div>
)
}
使用Hook实现加减
最新推荐文章于 2022-08-11 09:40:44 发布