我有一个 react native 屏幕,我想在其中使用 react native 可折叠 Accordion 组件来显示 Assets 列表。在 Accordion 所需的 rendercontent
属性中,我传入了一个在屏幕组件内定义的函数 sellAsset
,我在其中使用 this
关键字来引用屏幕成分。但它不起作用,总是告诉我 this.sellAsset 不是一个函数
。请参阅下面的代码。
尝试了一些函数绑定(bind)但没有成功。传递给 Accordion 组件的 this
似乎并未指向屏幕组件。
那么如何正确调用this.sellAsset
呢?
renderContent(item) {
return (
<View style={[styles.imageContent]}>
<View style={[styles.detailContainer, {paddingVertical: 0}]}>
<Image source={getImage(_.get(item, ['Asset', 'image']))} resizeMode="contain" style={styles.assetImage}/>
</View>
<View style={styles.priceContainer}>
<CustomSignInButton
text="SELL"
onPress={() => {this.sellAsset();}}
buttonBackgroundColor="transparent"
buttonBorderColor="white"
buttonTextColor="white"
buttonHeight={30}
/>
</View>
</View>
);
}
render() {
return (
<LinearGradient colors={[Colors.splashGradient.top, Colors.splashGradient.middle, Colors.splashGradient.bottom]}
style={{flex: 1}}>
<View style={styles.container}>
<IOSStatusBar backgroundColor="transparent"/>
{this.state.transactionDetails !== null ?
(this.state.transactionDetails.length > 0 &&
<Accordion sections={this.state.transactionDetails} renderHeader={this.renderHeader}
renderContent={this.renderContent} underlayColor={Colors.rowSeparatorBlue}
/>
) : <View/>
}
</View>
</LinearGradient>
);
}
}
最佳答案
如果我理解正确的话 sellAsset() 是您屏幕组件上的一种方法?
您有两个选择:
<强>1。将两个方法绑定(bind)到此
class YourScreen extends React.Component {
constructor(props) {
this.renderContent = this.renderContent.bind(this);
this.sellAsset = this.sellAsset.bind(this);
}
sellAsset() { ... }
renderContent() { ... }
}
<强>2。使用箭头函数
class YourScreen extends React.Component {
sellAsset = () => { ... }
renderContent = (item) => { ... }
}
关于javascript - 如何在react-native-collapsible Accordion 组件中使用 `this`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54121142/