0

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>
    );
  }
}
  • `onPress={() => this.sellAsset()}` or `onPress={this.sellAsset}`, but you probably know. Can you share `sellAsset()` function definition? – Milore Jan 10 '19 at 07:49
  • 1
    @Milore Thanks for your answer. It was the `this` binding problem and fixed it in the constructor – Jingyu Qian Jan 11 '19 at 05:25

1 Answers1

2

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) => { ... }
}
dentemm
  • 6,231
  • 3
  • 31
  • 43