求和案例(纯react版本)

新建react项目

create-react-app,新建react项目。
当前,create-react-app创建的react项目默认使用的是react@18。本项目要使用react17,因此手动降版本,npm install --save react@17 react-dom@17

实现求和案例

在这里插入图片描述

实现求和案例,代码变更涉及的文件有:

  1. 入口文件index.js
  2. 入口组件App.js
  3. 求和组件components/Counter/index.jsx

入口文件index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render( <App />,document.getElementById("root"));

App.js(入口组件)

import React, { Component } from 'react'
import Counter from "./components/Counter";

export default class App extends Component {
  render() {
    return (
      <div>
        <Counter/>
      </div>
    )
  }
}

Counter/index.jsx(Counter组件)

import React, { Component } from 'react'

export default class Counter extends Component {

    state = {count:0}

    increment = () => {
        const {value} = this.selectEl;
        const {count} = this.state;
        this.setState({count:count+Number(value)});
    }
    decrement = () => {
        const {value} = this.selectEl;
        const {count} = this.state;
        this.setState({count:count-Number(value)});
    }
    incrementOdd = () => {
        const {value} = this.selectEl;
        const {count} = this.state;
        if(count % 2 !== 0){
            this.setState({count:count+Number(value)});
        }
    }
    incrementWait = () => {
        const {value} = this.selectEl;
        const {count} = this.state;
        setTimeout(() => {
            this.setState({count:count+Number(value)});
        },1000)
    }

  render() {
    const {count} = this.state;
    const {increment,decrement,incrementOdd,incrementWait} = this;
    return (
        <div>
            <h2>当前求和为{count}</h2>
            <select ref={c => this.selectEl = c}>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
            </select>&nbsp;
            <button onClick={increment}>+</button>&nbsp;
            <button onClick={decrement}>-</button>&nbsp;
            <button onClick={incrementOdd}>和为奇数时加</button>&nbsp;
            <button onClick={incrementWait}>等一等再加</button>
        </div>
    )
  }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值