React组件绑定this的几种方式

在React中使用class定义组件时如果不注意this的指向问题,会带来一些麻烦。

绑定this主要有下面两种方法:

1. bind()

在class中定义函数,然后在构造方法中使用bind()绑定当前的组件对象。

class MyComponent extends React.Component {
    constructor(props) {
        super(props) ;
        this.handleClick = this.handleClick.bind(this) ;
    }
    handleClick() {
        //...
    }
    render() {
        return (
            <div>
                <button onClick={this.handleClick}>点击</button>
            </div>
        )
    }
}

2. 箭头函数

箭头函数中的this指向定义函数定义时所在的执行环境。而不是运行时所在的环境。

class MyComponent extends React.Component {
    constructor(props) {
        super(props) ;

    }
    handleClick = () => {
        //...
    }
    render() {
        return (
            <div>
                <button onClick={this.handleClick}>点击</button>
            </div>
        )
    }
}

组件中,哪些函数需要绑定当前组件对象呢,主要有:

1. 事件处理函数

2. 作为自定义属性传入子组件的函数

class MyComponent extends React.Component {
    constructor(props) {
        super(props) ;

    }

    commentAdd = () => {
        //...
    }
    render() {
        return (
            <div>
                   <CommentList CommentAdd={this.commentAdd} />
            </div>
        )
    }
}

CommentList是一个子组件,从父组件中传入了一个函数作为这个子组件的自定义属性。

3. 异步操作的回调函数

class MyComponent extends React.Component {
    constructor(props) {
        super(props) ;
        this.state = {

            title: 'hello world'
        }

    }


    componentDidMount() {
        setTimeout((function() {
            this.setState({
                title: '你好,世界'
            })
        }).bind(this), 1000)
    }

    render() {
        return (
            <div>
                <h1>{this.state.title}</h1>
            </div>
        )
    }
}
ReactDOM.render(<MyComponent/>, document.querySelector('#app'))

setTimeout()的第一个参数是一个回调函数。此时这个回调函数需要绑定当前的组件对象,因为回调函数内需要组件的一些方法和属性。

总结

凡是组件内自定义的函数,都要绑定组件对象。而且最好使用箭头函数定义函数。这样函数内部的this直接指向当前的组件对象。

组件中不能使用立即执行的函数。

猜你喜欢

转载自www.cnblogs.com/qinney1109/p/11200280.html