React 实现一个计数器

新建组件 views/components/count.js

import  {
    
     Component } from 'react'

export default class Count extends Component {
    
    

	state = {
    
    count:0}

	//加法
	increment = ()=>{
    
    
		const {
    
    value} = this.stepNum
    const {
    
     count} = this.state
		this.setState({
    
    count:count+value*1})
	}
	//减法
	decrement = ()=>{
    
    
		const {
    
    value} = this.stepNum
    const {
    
     count} = this.state
		this.setState({
    
    count:count-value*1})
	}
	// 奇数再加
	incrementIfOdd = ()=>{
    
    
		const {
    
    value} = this.stepNum
    const {
    
     count} = this.state
		if(count % 2 !== 0){
    
    
			this.setState({
    
    count:count+value*1})
		}
	}
  // 偶数再加
	incrementIfEven = ()=>{
    
    
		const {
    
    value} = this.stepNum
    const {
    
     count} = this.state
		if(count % 2 == 0){
    
    
			this.setState({
    
    count:count-value*1})
		}
	}
	// 异步加
	incrementAsync = ()=>{
    
    
		const {
    
    value} = this.stepNum
    const {
    
     count} = this.state
		setTimeout(()=>{
    
    
			this.setState({
    
    count:count+value*1})
		},500)
	}

	render() {
    
    
    const {
    
     count} = this.state
		return (
			<div>
				<h1>计数器值为:{
    
    count}</h1>
				<select ref={
    
    c => this.stepNum = c}>
					<option value="1">1</option>
					<option value="2">2</option>
					<option value="3">3</option>
					<option value="4">4</option>
					<option value="5">5</option>
					<option value="6">6</option>
				</select>&nbsp;
				<button onClick={
    
    this.increment}>+</button>&nbsp;
				<button onClick={
    
    this.decrement}>-</button>&nbsp;
				<button onClick={
    
    this.incrementIfOdd}>当前求和为奇数再加</button>&nbsp;
				<button onClick={
    
    this.incrementIfEven}>当前求和为偶数再加</button>&nbsp;
				<button onClick={
    
    this.incrementAsync}>异步加</button>&nbsp;
			</div>
		)
	}
}

App.js 引入组件:

import './assets/css/App.css';
import Count from './views/components/count'
function App () {
    
    
  return (
    <div className="App">
      <Count />
    </div>
  );
}
export default App;

页面效果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/HH18700418030/article/details/130382978