2

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.

sergdenisov
  • 8,327
  • 9
  • 48
  • 63
Eugene
  • 87
  • 4

2 Answers2

2

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.

Vencovsky
  • 28,550
  • 17
  • 109
  • 176
2

It works because:

  1. You initialized state as a class property, so you don't need a constructor.
  2. You call changeToDefaultImg() inside an anonymous arrow function, so you don't need to use Function.prototype.bind() to save a this.

Read this article for more explanations.

sergdenisov
  • 8,327
  • 9
  • 48
  • 63