this in React Native class method

Viewed 1349

I have this React Native component:

type Props = { image: string, onPress: Function, text: string, title: String };
type States = { loadError: boolean };

export default class ProductRow extends Component<Props, States> {
  state = {
    loadError: false
  };

  changeToDefaultImg() {
    this.setState({ loadError: true });
  }

  render() {
    let img = this.state.loadError ? (
      <SImage source={PLACEHOLDER} style={styles.placeholderImg} />
    ) : (
      <Image
        source={{ uri: this.props.image }}
        indicator={ProgressCircleSnail}
        indicatorProps={{ color: mainDark }}
        onError={() => this.changeToDefaultImg()}
        resizeMode="contain"
        style={styles.image}
        threshold={0}
      />
    );

    return (
      // JSX
    );
  }
}

You can see that I haven't written:

constructor(props) { 
  super(props)
  this.changeToDefaultImg = this.changeToDefaultImg.bind(this); 
}

But I can use this function without any errors.

Please, explain to me, why it works.

2 Answers

There is two ways to make a class function work.

1. Declare it as an arrow function

If you declare changeToDefaultImg as changeToDefaultImg = () = {...} and pass it as onError={this.changeToDefaultImg}, it will work normally.

2. Calling the function inside an arrow function

If you call it inside a arrow function like onError={() => this.changeToDefaultImg()}, it will also work normally.

As you can see, you are doing the second case. If you don't use arrow functions, you will be getting the wrong this.

You should notice that using the first way is better because you don't create a instance of an arrow function on every render like in the second way.

You should take a look at some related question.

Related