【问题标题】:this in React Native class methodReact Native 类方法中的 this
【发布时间】:2019-11-12 10:37:28
【问题描述】:

我有这个 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); 
}

但我可以毫无错误地使用此功能。

请向我解释一下,为什么它会起作用。

【问题讨论】:

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


    【解决方案1】:

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

    1.将其声明为箭头函数

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

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

    如果你在onError={() =&gt; this.changeToDefaultImg()}这样的箭头函数中调用它,它也能正常工作。

    如您所见,您正在执行第二种情况。如果你不使用箭头函数,你会得到错误的this

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

    你应该看看related question

    【讨论】:

      【解决方案2】:

      之所以有效,是因为:

      1. 你把initialized state 当作class property,所以你不需要constructor
      2. 您在匿名arrow function 中调用changeToDefaultImg(),因此您无需使用Function.prototype.bind() 来保存this

      阅读this article了解更多解释。

      【讨论】:

        猜你喜欢
        • 2018-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-06
        相关资源
        最近更新 更多