这在React Native类方法中

时间:2019-07-01 19:20:22

标签: javascript react-native jsx es6-class arrow-functions

我有这个React Native组件:

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
    );
  }
}

您可以看到我还没有写:

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

但是我可以正常使用此功能。

请向我解释为什么它起作用。

2 个答案:

答案 0 :(得分:2)

有两种方法可以使类函数起作用。

1。声明为箭头功能

如果将changeToDefaultImg声明为changeToDefaultImg = () = {...}并将其传递为onError={this.changeToDefaultImg},它将正常工作。

2。在箭头函数内调用该函数

如果您在onError={() => this.changeToDefaultImg()}之类的箭头函数中调用它,它也将正常工作。

如您所见,您正在做第二种情况。如果您不使用箭头功能,则会得到错误的this

您应该注意到,使用第一种方法会更好,因为您不会像第二种方法那样在每个渲染上创建箭头函数的实例。

您应该看看一些related question

答案 1 :(得分:2)

它之所以有效,是因为:

  1. initialized stateclass property,因此您不需要constructor
  2. 您在匿名arrow function内致电changeToDefaultImg(),因此您无需使用Function.prototype.bind()来保存this

阅读this article了解更多说明。