繁体   English   中英

在React Native FlatList中按下组件时如何更改其颜色

[英]How to change color of an component when its pressed in React Native FlatList

我一直在尝试开发一个列表,其中包含数据源中的卡片和列表项。 我已经成功提出了该列表,但是我想要实现的是,只要用户触摸列表中的某个项目,该项目的颜色就会改变。

最重要的是,应该只选择一项 如何实现呢? 我已经通过使用redux动作和reducer掌握了数据的价值。 但是,我不知道如何实现这一选择过程。

我的flatList代码:

 <FlatList
    horizontal={true}
    data={this.qtyList}
    keyExtractor={item => item.id.toString()}
    showsHorizontalScrollIndicator={false}
    renderItem={({ item }) => (
            <TouchableHighlight 
            onPress={() => {

            }}
            >
            <Card
            containerStyle={{  borderRadius: 5 }}
            >
            <Text>
            {item.qty}
            </Text>
            </Card>
        </TouchableHighlight>
    )}
/>

请逐步说明,因为我完全是个初学者。 我不想在redux的帮助下完成此操作,因此组件级别的状态将是非常有用的。

您应将所选项目的ID存储在状态中:

<TouchableHighlight 
  onPress={() => {
    this.setState({ itemSelected: item.id }) <== your item must have a unique id
  }}
>

然后,例如,在您的卡组件中,您可以执行以下操作:

<Card
  containerStyle={{
    borderRadius: 5,
    backgroungColor: this.state.itemSelected === item.id ? 'red', 'white',
  }}
>

另外,您必须将extraData={this.state}添加到您的单位列表中。 这是文档的链接

您需要一个函数来设置用户单击FlatList项时的状态。 当状态更改时,组件样式将更改以显示所选项目。 并且您应该将extraData设置为FlatList以在状态更改时进行呈现。

class Second extends React.Component {    
    constructor(props) {
        super(props);
        this.state = {
            selectedItem: null
        };
    }

    onPressHandler(id) {
        this.setState({selectedItem: id});
    }

    render() {
        return (
            <View>
                <FlatList
                    extraData={this.state.selectedItem} //Must implemented
                    horizontal={true}
                    data={qtyList}
                    keyExtractor={item => item.id.toString()}
                    showsHorizontalScrollIndicator={false}
                    renderItem={({item}) => (
                        <TouchableOpacity
                            onPress={() => this.onPressHandler(item.id)}>
                            <Card
                                containerStyle={this.state.selectedItem === item.id ? {
                                    borderRadius: 5,
                                    backgroundColor: "#000000"
                                } : {borderRadius: 5, backgroundColor: "#a1a1a1"}}>
                                <Text>{item.qty}</Text>
                            </Card>
                        </TouchableOpacity>
                    )}
                />
            </View>
        );
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM