React component binding this in several ways

When using the class definition of component React if not pay attention to this point in question, it will bring some trouble.

There are two ways to bind this major:

1. bind()

Function is defined in the class, then the constructor binding current component object using bind () in.

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. Functions arrow

Arrow pointing to the definition of the function of this function is defined where the execution environment. Rather than where the runtime environment.

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

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

Component, which functions needed to bind the current component object it, are:

1. The event handler

2 as a function of the custom property of the incoming subassembly

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

    }

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

CommentList is a sub-assembly, passed as a function of this subassembly custom properties from the parent component.

3. Asynchronous operation callback

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'))

The first parameter setTimeout () is a callback function. In this case the current needs to be bound to this callback component object, because of the need methods and properties of components within the callback function.

to sum up

Those who function within custom components, should be binding component object. Further preferred to use the arrow function definition function. Such a function of this current directly to the interior of the component objects.

Components can not be used to perform the function immediately.

Guess you like

Origin www.cnblogs.com/qinney1109/p/11200280.html
Recommended