在 React Native 的 Flat-list 的 RenderItem 中更新被点击的按钮状态

Updating button state which is clicked, inside RenderItem of Flat-list, in React Native

我是 React Native 的新手,正在尝试完成如下所示的操作,其中来自服务器的简单列表在带有按钮的列表中呈现。单击按钮后,按钮将被禁用并且不透明度将更改。

我能够创建 UI,但是当我单击任何显示“加入”的按钮时,之前单击的按钮会将其状态重置为原始状态。也就是说,只有一个按钮一直显示点击状态。

所以我的代码是这样的

constructor(props){
   super(props);
   this.state = {selectedIndices: false, groupsData: ''};
}

渲染方法中的 Flatlist 看起来像

<FlatList style={styles.list}
 data={this.state.groupsData}
 keyExtractor={(groups) => {
     return groups.groupId.toString();
 }}
 renderItem={(item, index) => {
     return this.renderGroupItem(item);
 }}/>

RenderGroupItem

renderGroupItem = ({item} )=>(
    <GroupItem group = {item} style={{height: '10%'}} onPress = {() => this.onJoinButtonPress(item)} 
    index = {this.state.selectedIndices}/>
)

onJoinButtonPress

onJoinButtonPress = (item) =>{
    this.setState({selectedIndices: true});
}

GroupItem

render(){
        if(this.props.group.groupId === this.props.index){
            return(
                <View style = {[styles.container]}>
                    <Image source={{uri: 'some Image Url'}} style={styles.roundImage}/>
                    <Text style={styles.groupText}>{this.props.group.name}</Text>
                    <View >
                        <TouchableOpacity style = {[styles.button, {opacity: 0.4}]} activeOpacity = { .5 } onPress = {this.props.onPress} 
                        disabled = {true}>
                            <Text style = {{color: 'white', fontSize: 12}}>Joined</Text>
                        </TouchableOpacity>
                    </View>                
                </View>
            );
        }else{
            return(
                <View style = {styles.container}>
                    <Image source={{uri: 'Some Image Url'}} style={styles.roundImage}/>
                    <Text style={styles.groupText}>{this.props.group.name}</Text>
                    <View >
                        <TouchableOpacity style = {styles.button} activeOpacity = { .5 } onPress = {this.props.onPress}>
                            <Text style = {{color: 'white', fontSize: 12}}>Join</Text>
                        </TouchableOpacity>
                    </View>                
                </View>
            );
        }
    }

现在我知道我需要传递一个数组或 hasmap,其中包含已单击项目的映射,但我不知道该怎么做。在这里需要绝望的帮助。

在 groupsData 中维护一个布尔值后,我能够克服上述问题。选择后,我更新 groupsData 中的布尔值“groupsJoined”并更新将调用渲染的 groupsData 的状态。在 GroupsItem class 中,我添加了一个检查,如果来自 props 的数据将 joinedGroups 设为 true,则呈现选定状态,否则呈现非选定状态。

礼貌https://hackernoon.com/how-to-highlight-and-multi-select-items-in-a-flatlist-component-react-native-1ca416dec4bc