简体   繁体   中英

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:

应用截图

You need to create a child component with its own state.

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>
  }
}

Then you just need to add it inside your renderItem method.

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

Here's a working example

I hope it helps ! Feel free to add comments if you're still stuck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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