Java 杂谈网页前端后台技巧(CSS+HTML)让前端飞

React官网学习实践 - 事件处理

2018-11-05  本文已影响5人  张中华

React 元素的事件处理和 DOM元素的很相似。但是有一点语法上的不同:

<button onclick="activateLasers()">
  Activate Lasers
</button>

React 中稍稍有点不同:

<button onClick={activateLasers}>
  Activate Lasers
</button>

实例:

从实例中可以看出,当修改state中的某个变量时,componentWillUpdate, componentDidUpdate也会相应的执行。
注意:
此处的函数handleClick(), 在使用类似匿名函数时(不是很清楚如何称呼)省略了参数的括号,我加上括号时,同样可以达到效果。

 handleClick() {
        this.setState((prevState) => ({
            isToggleOn: !prevState.isToggleOn
        }));
    }

你必须谨慎对待 JSX 回调函数中的 this,类的方法默认是不会绑定this 的。如果你忘记绑定 this.handleClick 并把它传入 onClick, 当你调用这个函数的时候 this 的值会是 undefined

这并不是 React 的特殊行为;它是函数如何在 JavaScript 中运行的一部分。通常情况下,如果你没有在方法后面添加 () ,例如 onClick={this.handleClick},你应该为这个方法绑定 this.

code:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {isToggleOn: true};

        // This binding is necessary to make `this` work in the callback
        this.handleClick = this.handleClick.bind(this);
    }
    componentWillMount () {
        console.log('this is in componentWillMount method.');

    }
    componentDidMount () {
        console.log('this is in componentDidMount method.');
    }
    componentWillReceiveProps (nextProps) {
        console.log('this is in componentWillReceiveProps method.');
    }
    // shouldComponentUpdate (nextProps,nextState) {
    //     console.log('this is in shouldComponentUpdate method.');
    // }
    componentWillUpdate (nextProps,nextState) {
        console.log('this is in componentWillUpdate method.');
    }
    componentDidUpdate (prevProps,prevState) {
        console.log('this is in componentDidUpdate method.');
    }
    handleClick() {
        this.setState(prevState => ({
            isToggleOn: !prevState.isToggleOn
        }));
    }

    render() {
    return (
        <div>
            <button onClick={this.handleClick}>
                {this.state.isToggleOn ? 'ON' : 'OFF'}
            </button>
        </div>
    );
  }
    componentWillUnmount () {
        console.log('this is in componentWillUnmount method.');
    }
}

export default App;
上一篇 下一篇

猜你喜欢

热点阅读