react-native - (React Native)在 onPress() 之后将颜色更改为文本
问题描述
我有一个抽屉,里面有一些动态创建的文本元素。
我想从抽屉中选择一个项目,“显示所选项目”(例如更改该项目文本的颜色)并在选择另一个项目时将其重新更改为默认值。
我想“更改 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();
};
}
解决方案
如果我理解正确,您想更改所选项目的颜色
//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()}
/>