零经验学 react 的第7天 - 事件绑定

3 阅读2分钟

一、要点

  • 使用 onClick 进行事件绑定,注意不要加 ()
  • 传参需要使用 bind 进行传参
  • 在 React 中所有事件都会传播,除了 onScroll,它仅适用于你附加到的 JSX 标签
  • e.stopPropagation() 阻止触发绑定在外层标签上的事件处理函数。
  • e.preventDefault() 阻止少数事件的默认浏览器行为。例如 form 元素的 onSubmit 事件带来的浏览器重载行为

二、代码示例

function 组件示例

import { useState } from "react";

function Test1 () {
    const [a, setA] = useState(1);
    const [b, setB] = useState(11);
    const [arr, setArr] = useState([1, 2]);
    const [arr1, setArr1] = useState([22, 33]);
    const [obj, setObj] = useState({x: 1, y: 2});
    const [show, setShow] = useState(true);

    // 事件绑定
    const increaseA = (num, e) => {
        console.log("事件对象:", e);
        return () => {
            setA(a + num);
        }
    }
    return (
        <div className="test1-box">
            <p>Test1</p>
            <div>
                {/* 事件绑定 */}
                <div>
                    <p>事件绑定</p>
                    <div>
                        <button type="button" onClick={(e) => increaseA(10, e)}>a+10</button>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default Test1;

class 组件示例

import React from 'react';

class Test2 extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            a: 1,
            b: 11,
            arr: [1,2],
            arr1: [22,33],
            obj: {x: 1, y: 2},
            show: true
        }
    }
    increaseA(num, e) {
        console.log("事件对象:", e);
        const _a = this.state.a;
        this.setState({
            a: _a + num
        });
    }
    render() {
        return(
            <div className="test2-box">
                <p>Test2</p>
                <div>
                    {/* 事件绑定 */}
                    <div>
                        <p>事件绑定</p>
                        <div>
                            <button type="button" onClick={this.increaseA.bind(this, 10)}>a+10</button>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}
export default Test2;

案例

  • 点击不同 tab,来切换两种面板内容
  • 点击面板内容的某项删除按钮,进行内容项删除

function 组件

// function 组件
import { useState } from "react";
function Example() {
    const [arr1, setArr1] = useState([
        {id: 1, name: 'good1'},
        {id: 2, name: 'good2'},
        {id: 3, name: 'good3'}
    ]);
    const [arr2, setArr2] = useState([
        {id: 1, name: 'price1'},
        {id: 2, name: 'price2'},
        {id: 3, name: 'price3'}
    ]);
    const [tab, setTab] = useState(1);
    const deleteItem = (id) => {
        let arr = tab === 1 ? arr1 : arr2;
        let _arr = arr.filter(item => item.id !== id);
        if(tab === 1) {
            setArr1(_arr);
        } else {
            setArr2(_arr);
        }
    }
    const renderArr1 = () => {
        return arr1.map((item, index) => {
            return(
                <div key={item.id}>
                    <span>{item.name}</span>
                    <button type="button" onClick={() => deleteItem(item.id)}>Delete</button>
                </div>
            )
        })
    }
    const renderArr2 = () => {
        return arr2.map((item, index) => {
            return(
                <div key={item.id}>
                    <span>{item.name}</span>
                    <button type="button" onClick={() => deleteItem(item.id)}>Delete</button>
                </div>
            )
        })
    }
    const renderContent = () => {
        tab === 1 ? renderArr1() : renderArr2();
    }

    return(
        <div>
            <button type="button" onClick={() => setTab(1)}>show arr1 content</button><br/>
            <button type="button" onClick={() => setTab(2)}>show arr2 content</button>
            <div>
                {renderContent()}
            </div>
        </div>
    )
}
export default Example;

class 组件

// class 组件
import React from 'react';

class Example extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            tab: 1,
            arr1: [
                { id: 1,name: 'good1'},
                {id: 2,name: 'good2'},
                {id: 3,name: 'good3'}
            ],
            arr2: [
                {id: 1,name: 'price1'},
                {id: 2,name: 'price2'},
                {id: 3,name: 'price3'}
            ],
        }
    }
    deleteItem(id) {
        let arr = this.state.tab === 1 ? this.state.arr1 : this.state.arr2;
        let _arr = arr.filter(item => item.id !== id);
            if(this.state.tab === 1) {
                this.setState({
                    arr1: _arr
                });
            } else {
            this.setState({
                arr2: _arr
            });
        }
    }
    renderArr1() {
        return this.state.arr1.map(item => {
            return (
                <div key={item.id}>
                    <span>{item.name}</span>
                    <button type="button" onClick={this.deleteItem.bind(this, item.id)}>Delete</button>
                </div>
            )
        });
    }
    renderArr2() {
        return this.state.arr2.map(item => {
            return (
                <div key={item.id}>
                    <span>{item.name}</span>
                    <button type="button" onClick={this.deleteItem.bind(this, item.id)}>Delete</button>
                </div>
            )
        });
    }

    renderContent(){
        return this.state.tab === 1 ? this.renderArr1() : this.renderArr2();
    }
    render() {
        return (
            <div>
                <button type="button" onClick={() => this.setState({tab: 1})}>show arr1 content</button><br/>
                <button type="button" onClick={() => this.setState({tab: 2})}>show arr2 content</button>
                <div>
                    {this.renderContent()}
                </div>
            </div>
        )
    }
}
export default Example;