【问题标题】:(React Native) Change color to a text after onPress() it(React Native)在 ​​onPress() 之后将颜色更改为文本
【发布时间】:2019-08-01 10:37:24
【问题描述】:

我有一个抽屉,里面有一些动态创建的文本元素。
我想从抽屉中选择一个项目,“显示所选项目”(例如更改该项目文本的颜色)并在选择另一个项目时将其重新更改为默认值。

我想“更改 onPress”的文本位于 <TouchableWithoutFeedback> 标记内(我正在使用 react-native-render-html 渲染一些 HTML 代码)

 <FlatList
          ItemSeparatorComponent={this.FlatListItemSeparator}
          data={this.state.data}
          renderItem={({ item }) => (
            //on touch --> open article (call _onTextPress)
            <TouchableWithoutFeedback onPress={this.navigateToScreen('Category', {id: item.id, title: item.name})}>
              <View style={styles.categories}>
                <HTML html={'<p style="color:#fd3a18; font-size:20px;"><strong>'+item.name+'</strong></p>\n'}/>
              </View>
            </TouchableWithoutFeedback>
          )}
          keyExtractor={({ id }, index) => id.toString()}
        />

  navigateToScreen(routeName, params) { 
    return () => { 
      this.props.navigation.dispatch(NavigationActions.navigate({ routeName, params }))
      this.props.navigation.closeDrawer();

    };
  }

【问题讨论】:

    标签: react-native text react-navigation onpress


    【解决方案1】:

    如果我理解正确,您想更改所选项目的颜色

    //Add Selected Item to the State
    state = {selectedItemId:'myId'}
    // Change The State Whenever Selected
     navigateToScreen(routeName, params) { 
        this.setState({selectedItemId:params.id})
        return () => { 
          this.props.navigation.dispatch(NavigationActions.navigate({ routeName, params }))
          this.props.navigation.closeDrawer();
    
        };
      }
    

    现在有条件地改变颜色。

              <FlatList
              ItemSeparatorComponent={this.FlatListItemSeparator}
              data={this.state.data}
              renderItem={({ item }) => (
                //on touch --> open article (call _onTextPress)
                <TouchableWithoutFeedback onPress={this.navigateToScreen('Category', {id: item.id, title: item.name})}>
                  <View style={styles.categories}>
                    <HTML html={`<p style="color:${this.state.selectedItemId == item.id ? "red" : "#fd3a18"}; font-size:20px;"><strong>'+item.name+'</strong></p>\n`}/>
                  </View>
                </TouchableWithoutFeedback>
              )}
              keyExtractor={({ id }, index) => id.toString()}
            />
    

    【讨论】:

    • 感谢您的回答 :) 有一个问题...我作为参数传递的 id 不是我按下的元素的 id...我该如何传递它?
    • @AndreaFavero 你能在你的帖子中显示 this.state.data 吗?
    猜你喜欢
    • 1970-01-01
    • 2017-06-29
    • 2020-02-24
    • 2015-11-27
    • 2021-05-23
    • 2023-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多