react中的事件绑定

350 阅读1分钟

事件绑定

我习惯用class,所以给了class的示例

视频教程地址

web/react/vue/ts

image.png

  • React 事件的命名采用小驼峰式(camelCase),而不是纯小写。
  • 使用 tsx语法时你需要传入一个函数作为事件处理函数,而不是一个字符串。
import React, {Component} from "react";

interface IState {
    numberList: number[]
}

export default class Bind extends Component<any, IState> {

    constructor(props: any, context: any) {
        super(props, context);
        this.state = {
            numberList: [1, 2, 3, 4, 5]
        }
    }

    delete = (index: number) => {
        // 更新state是异步的,在并发下是有问题的
        // 一般情况下人的手速不会那么快,所以这么写也是可以正常进行的,我写惯了这么写
        this.setState({
            numberList: this.state.numberList.filter((_, i) => i !== index)
        })
    }

    render() {
        return (
            <ul>
                {
                    this.state.numberList.map((num, index) => (
                        <li>
                            {num}
                            <button
                                onClick={this.delete.bind(this, index)}
                            >
                                delete bind
                            </button>
                            <button
                                onClick={() => {
                                    this.delete(index)
                                }}
                            >
                                delete
                            </button>
                        </li>
                    ))
                }
            </ul>
        )
    }
}
  • 定义state,用来提供需要渲染的数据
  • 定义点击事件
  • 绑定事件
  • 更新state
  • 更新ui