仅更改 FlatList 的 onPressed 项的样式 [英] Change the style of only onPressed item of FlatList
问题描述
我一直在尝试更改 Flatlist 的 selected(onPress) 项目的颜色,但它正在更改整个列表的颜色.我添加了以下代码:
I've been trying to change the color of the selected(onPress) item of the Flatlist but it's changing the color of whole list. I've added the code below:
class SelectionForm extends Component {
constructor(props) {
super(props);
this.state = {
textColor: '#333'
};
}
typeSelected(value) {
Alert.alert(value);
this.setState({
textColor: 'green'
});
}
render() {
return (
<View>
<FlatList
data={[
{ utId: '1', utName: 'Guest' },
{ utId: '2', utName: 'Faculty' },
{ utId: '3', utName: 'Student' }
]}
renderItem={
({ item }) =>
<Text
style={[
styles.userListText,
{
backgroundColor: this.state.bgColor,
color: this.state.textColor
}]}
onPress={() => this.typeSelected(item.utId)}
>
{item.utName}
</Text>
}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
}
const styles = StyleSheet.create({
userListText: {
fontSize: 14,
color: '#333',
paddingTop: 10,
paddingBottom: 10,
borderBottomWidth: 1,
borderColor: '#eee'
}
});
export default SelectionForm;
我正在使用文本来显示列表.onPress 列表中的文本,我获得了单击项的值,但所有列表项的样式都在更改.
I'm using Text to display the list. onPress the Text from the list, I'm getting the value of the clicked item but the style is changing for all list items.
推荐答案
你应该让你的代码依赖于你想要改变颜色的项目的 id
.
You should make your code depend upon the id
of item for which you want to change the color.
你的状态应该有一个标识符来跟踪当前按下的项目,比如 itemPressed
应该用一个任意值初始化,比如 -1
以便它不表示任何项目列表.
Your state should have a identifier to track currently pressed item say itemPressed
which should be initialized with an arbitary value say -1
so that it doesnt signifies any item in the list.
所以你的 typeSelected
应该是这样的:
so your typeSelected
should look like this:
typeSelected(value) {
Alert.alert(value);
this.setState({
itemPressed: value
});
}
和您的 Text
组件应如下所示:
and your Text
component should look like :
<Text
style={[
styles.userListText,
{
backgroundColor: this.state.bgColor,
color: this.state.itemPressed === item.utId ? 'green' : 'black'
}]}
onPress={() => this.typeSelected(item.utId)}
>
希望这会有所帮助.快乐编码 :)
Hope this helps. Happy Coding :)
这篇关于仅更改 FlatList 的 onPressed 项的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!