这在 React Native class 方法中
this in React Native class method
我有这个 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);
}
但是我可以毫无错误地使用这个函数。
请向我解释一下它为什么有效。
有两种方法可以使 class 函数起作用。
1.声明为箭头函数
如果您将changeToDefaultImg
声明为changeToDefaultImg = () = {...}
并将其作为onError={this.changeToDefaultImg}
传递,它将正常工作。
2。在箭头函数中调用函数
如果像onError={() => this.changeToDefaultImg()}
一样在箭头函数中调用它,它也能正常工作。
如你所见,你做的是第二种情况。如果你不使用箭头函数,你会得到错误的 this
.
您应该注意到使用第一种方式更好,因为您不会像第二种方式那样在每次渲染时都创建箭头函数的实例。
你应该看看一些 。
之所以有效,是因为:
- 你initialized
state
as a class property, so you don't need a constructor
.
- 您在匿名 arrow function, so you don't need to use
Function.prototype.bind()
to save a this
中调用 changeToDefaultImg()
。
阅读 this article 以获得更多解释。
我有这个 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);
}
但是我可以毫无错误地使用这个函数。
请向我解释一下它为什么有效。
有两种方法可以使 class 函数起作用。
1.声明为箭头函数
如果您将changeToDefaultImg
声明为changeToDefaultImg = () = {...}
并将其作为onError={this.changeToDefaultImg}
传递,它将正常工作。
2。在箭头函数中调用函数
如果像onError={() => this.changeToDefaultImg()}
一样在箭头函数中调用它,它也能正常工作。
如你所见,你做的是第二种情况。如果你不使用箭头函数,你会得到错误的 this
.
您应该注意到使用第一种方式更好,因为您不会像第二种方式那样在每次渲染时都创建箭头函数的实例。
你应该看看一些
之所以有效,是因为:
- 你initialized
state
as a class property, so you don't need aconstructor
. - 您在匿名 arrow function, so you don't need to use
Function.prototype.bind()
to save athis
中调用changeToDefaultImg()
。
阅读 this article 以获得更多解释。