javascript - 如何在react-native-collapsible Accordion 组件中使用 `this`?

标签 javascript react-native expo react-native-collapsible

我有一个 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/

相关文章:

ios - 错误 ITMS-90596 : "Invalid Bundle. The asset catalog at ' Payload/ExpoKitApp. app/.bundle/Assets.car' 无法处理。”

javascript - 如何将expo react-native自定义字体应用到整个容器

javascript - 可拖动 slider HTML 和 JS?

用于拆分数据和计算总和的 JavaScript

javascript - 如何将下拉列表中的 <option> 标签的内容传递给服务器

ios - 用图像 react 原生 iOS 推送通知

android - Google Places API + React Native

javascript - 世博会,React Native 异步存储在热重载后重置?

javascript - 当窗口宽度小于1025时更改类

validation - 我如何验证最小字符数的 react native 文本输入