React Native:onPress:如何切换按钮文本和函数调用?

Ste*_*eve 2 button toggle react-native onpress

我有一个看起来像这样的按钮......

<View style={styles.addToFavoritesStyle}>
  <Button onPress={this.addToFavorites}>ADD TO FAVORITES</Button>
</View>

addToFavorites() {
  ...run some code
}
Run Code Online (Sandbox Code Playgroud)

用户按下按钮后,如何将按钮文本更改为"从收藏中删除",更改按钮样式,并调用其他功能?

ajt*_*yng 5

你想要利用国家.在组件中添加构造函数:

constructor(props) {
  super(props);
  this.state = {
    inFavorites: false
  }
}
Run Code Online (Sandbox Code Playgroud)

让你的按钮看起来像这样:

<Button onPress={this.addToFavorites}>
  {this.state.inFavorites ? "REMOVE FROM " : "ADD TO " + "FAVORITES"}
</Button>
Run Code Online (Sandbox Code Playgroud)

在您的addToFavorites()函数中添加一个调用来设置组件的状态:

this.setState({ inFavorites: true});
Run Code Online (Sandbox Code Playgroud)

这不是一个全包示例,但它将设置组件的状态.当他们从收藏夹中删除项目时,您必须再次设置状态.