How to use `this` in react-native-collapsible accordion component?

1.1k views Asked by At

I have a react-native screen, where I want to use react-native-collapsible accordion component to show a list of assets. In the required rendercontent prop of accordion, I pass in a function sellAsset defined inside the screen component where I use this keyword to refer to the screen component. But it didn't work, always telling me this.sellAsset is not a function. Please see the code below.

Tried some function binding but didn't work. It seems the this passed to the accordion component does not point to the screen component.

So how to call this.sellAsset correctly?

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

There are 1 answers

1
dentemm On BEST ANSWER

If I understand correctly sellAsset() is a method on your screen component?

You have two options:

1. Bind both methods to this

class YourScreen extends React.Component {

  constructor(props) {
    this.renderContent = this.renderContent.bind(this);
    this.sellAsset = this.sellAsset.bind(this);
  }

  sellAsset() { ... }

  renderContent() { ... }
}

2. Use arrow functions

class YourScreen extends React.Component {

  sellAsset = () => { ... }

  renderContent = (item) => { ... }
}