首页 > 解决方案 > React Native FlatList: Toggle State Value

问题描述

I am trying toggle text state from ACTIVE to INACTIVE (and vice versa) for each individual item in the FlatList. In the code below, the status toggles from true to false (and false to true) but the text in the app shows inactive and doesn't change.

import NameActionBar from '../components/NameActionBar';
        
        export default class MasterScreen extends Component {
            constructor(props) {
                super(props);
                this.state = {
                    dataSource: [],
                    status: false,
                };
            }
        
            componentDidMount() {
                this.getFreelancerList();
            }
        
    //Calling API to get list
            getFreelancerList() {
                let self = this;
                AsyncStorage.getItem('my_token').then((keyValue) => {
                    console.log('Master Screen (keyValue): ', keyValue); //Display key value
                    axios({
                        method: 'get',
                        url: Constants.API_URL + 'user_m/freelancer_list/',
                        responseType: 'json',
                        headers: {
                            'X-API-KEY': Constants.API_KEY,
                            'Authorization': keyValue,
                        },
                    })
                        .then(function (response) {
                            console.log('Response.Data: ===> ', response.data.data);
                            console.log('Response: ', response);
                            self.setState({
                                dataSource: response.data.data,
                            });
                        })
                        .catch(function (error) {
                            console.log('Error: ', error);
                        });
                }, (error) => {
                    console.log('error error!', error) //Display error
                });
            }
        
//Show the list using FlatList
            viewFreelancerList() {
                const { dataSource } = this.state;
                return (
                    <View>
                        {<FlatList
                            data={dataSource}
                            keyExtractor={({ id }, index) => index.toString()}
                            renderItem={({ item }) => {
                                return (
                                    <View style={styles.containerFreelancer}>
                                        <TouchableOpacity
                                            style={{ flex: 1 }}
                                            onPress={() => console.log(item.freelancer_name)}
                                        >
                                            <Text style={styles.textFreelancer}>{item.freelancer_name}</Text>
                                        </TouchableOpacity>
                                        <TouchableOpacity
                                            onPress={() => {
                                                const newStatus = !this.state.status;
                                                this.setState({
                                                    status: newStatus,
                                                });
                                                console.log('status: ', this.state.status);
                                            }}
                                        >
                                            <Text>{this.state.status ? "ACTIVE" : "INACTIVE"}</Text>
                                        </TouchableOpacity>
                                    </View>
                                );
                            }}
                        />}
                    </View>
                );
            }
        
            render() {
                return (
                    <>
                        <NameActionBar />
                        <ScrollView>
                            {this.viewFreelancerList()}
                        </ScrollView>
                    </>
                );
            }
        }

My issues are:

  1. How can I make the text toggle between active to inactive?

  2. How can I make the text toggle separately for each item in the FlatList? for example: Item 1: 'ACTIVE', Item 2: 'INACTIVE' etc.

Any help would be appreciated as I am still new to learning React Native.

Screenshot of the app below:

app screenshot

标签: javascriptreact-nativereact-native-flatlist

解决方案


您需要创建一个具有自己状态的子组件。

class FlatListComponent extends Component {
  state = {
    status: false
  }

  render() {
    <View style={styles.containerFreelancer}>
       <TouchableOpacity style={{ flex: 1 }} onPress={() => console.log(this.props.freelancer_name)}>
           <Text style={styles.textFreelancer}>{this.props.freelancer_name}</Text>
       </TouchableOpacity>
       <TouchableOpacity onPress={() => {
              const newStatus = !this.state.status;
              this.setState({
                status: newStatus,
              });
              console.log('status: ', this.state.status);
            }}
        >
            <Text>{this.state.status ? "ACTIVE" : "INACTIVE"}</Text>
      </TouchableOpacity>
    </View>
  }
}

然后你只需要将它添加到你的renderItem方法中。

<FlatList
  data={dataSource}
  keyExtractor={({ id }, index) => index.toString()}
  renderItem={({ item }) => <FlatListComponent {...item}/>
/>}

这是一个工作示例

我希望它有帮助!如果您仍然卡住,请随时添加评论


推荐阅读