Answer a question

I am a complete newbie in react native, react.js, and javascript. I am Android developer so would like to give RN a try.

Basically, the difference is in onPress;

This code shows 'undefined' when toggle() runs:

class LoaderBtn extends Component {
    constructor(props) {
        super(props);
        this.state = { loading: false };
    }

    toggle() {
        console.log(this.state);
        // let state = this.state.loading;
        console.log("Clicked!")
        // this.setState({ loading: !state })
    }

    render() {
        return (
            <Button style={{ backgroundColor: '#468938' }} onPress={this.toggle}>
                <Text>{this.props.text}</Text>
            </Button>
        );
    }
}

but this code works:

class LoaderBtn extends Component {
    constructor(props) {
        super(props);
        this.state = { loading: false };
    }

    toggle() {
        console.log(this.state);
        // let state = this.state.loading;
        console.log("Clicked!")
        // this.setState({ loading: !state })
    }

    render() {
        return (
            <Button style={{ backgroundColor: '#468938' }} onPress={() => {this.toggle()}}>
                <Text>{this.props.text}</Text>
            </Button>
        );
    }
}

Can you explain me the difference, please?

In Java / Kotlin we have method references, basically it passes the function if signatures are the same, like onPress = () => {} and toggle = () => {}

But in JS it doesn't work :(

Answers

The issue is that in the first example toggle() is not bound to the correct this.

You can either bind it in the constructor:

constructor(props) {
    super(props);
    this.toggle = this.toggle.bind(this);
    ...
    

Or use an instance function (OK under some circumstances):

toggle = () => {
    ...
}

This approach requires build changes via stage-2 or transform-class-properties.

The caveat with instance property functions is that there's a function created per-component. This is okay if there aren't many of them on the page, but it's something to keep in mind. Some mocking libraries also don't deal with arrow functions particularly well (i.e., arrow functions aren't on the prototype, but on the instance).

This is basic JS; this article regarding React Binding Patterns may help.

Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐