【问题标题】:Code activates all Switches at once. I only need one switch at a time代码一次激活所有开关。我一次只需要一个开关
【发布时间】:2020-11-15 00:24:53
【问题描述】:

我一直遇到错误,我是新来的本地反应。有人给出可能的解决方法吗?

    import React from 'react'
    import {StyleSheet, View,Text, Switch, Button, Alert, ScrollView, FlatList, SafeAreaView} from 'react-native'
    
    export default () => {
        const [isSwitchEnabled, setSwitch] = React.useState(false)
        const toggleSwitch = () => setSwitch(previousState => !previousState);
        const DATA = [
            {
                id: '1',
                title: 'Toggle Night Mode',
                switch: false
            },
            {
                id: '2',
                title: 'Remind me to take a break',
                switch: false
            },
            {
                id: '3',
                title: "Remind me when it's bedtime",
                switch: false
            },
    
        ];
    
        function Item({title}){
            return (
                <View>
                    <Text style={styles.text}> {title} </Text>
                    <Switch 
    
                    onValueChange= {toggleSwitch}
                    trackColor={{ false: "#767577", true: "#81b0ff" }}
                    thumbColor="#f5dd4b"
                    ios_backgroundColor="#3e3e3e"
                    value= {isSwitchEnabled}
                    />
                </View>
            )
        }
    
    
    
    
        function Header(){
            return(
                <View style = {styles.header}>
                    <Text style={styles.headertext}>Settings</Text>
                </View>
            )
        }
        
        return (
            <>
            <View>
                <SafeAreaView style ={styles.container}>
                    <FlatList
                        data = {DATA}
                        keyExtractor = {item => item.id}
                        renderItem = {( {item} ) => <Item title = {item.title}/> }
                        ListHeaderComponent = {Header()}
                    />
                </SafeAreaView>
            </View>
            <View> 
                <Button 
                title = "Clear Search History" 
                color = "#6fb6f0"    
                onPress = {() => Alert.alert('Food History Has Been Cleared!')}
                />
            </View>
            <View> 
                <Button 
                title = "Logout" 
                color = "#6fb6f0"    
                onPress = {() => Alert.alert('Successfully Logged Out!')}
                />
            </View>
    
            </>
        
        );
    }
    
    const styles = StyleSheet.create({
        container: {
            flex: 1,
            backgroundColor: '#fff',
            alignItems: 'center',
            justifyContent: 'center',
        },
        text: {
            fontSize: 20,
            fontWeight: "300"
        },
        headertext: {
            fontSize: 30,
            fontWeight: "300"
        },
        header:{
            flex:1,
            justifyContent: 'center',
            alignItems: 'center',
            padding: 10,
            backgroundColor: '#f5f5f5'
        }
    })

https://imgur.com/a/761PSjre

【问题讨论】:

    标签: react-native react-native-flatlist react-native-navigation


    【解决方案1】:

    您正在为每个项目附加一个状态,因此您的所有项目都根据该状态变化而变化。要修复它,请使每个项目成为具有内部状态的组件来控制它,或者为数据对象中的每个项目动态创建不同的状态。您必须为每个项目创建不同的状态。

    【讨论】:

    • 谢谢,但您能指导我如何将 useState 挂钩的值更改为数组吗?或者如何使每个项目成为一个组件?
    【解决方案2】:

    试试这个方法

    import React from 'react'
    import {StyleSheet, View,Text, Switch, Button, Alert, ScrollView, FlatList, SafeAreaView} from 'react-native'
        
        export default () => { 
    
        // use data set in default state
        const [data, setData] = React.useState([
                {
                    index: 1,
                    title: 'Toggle Night Mode',
                },
                {
                    index: 2,
                    title: 'Remind me to take a break',
                },
                {
                    index: 3,
                    title: "Remind me when it's bedtime",
                },
        
            ]);
    
            function toggleSwitch(value, index){
    
          const newData = [...data];
          const newData[index].isEnable = value;
          setData(newData);
    
        }
    
            function Item({item, index}) {
                return (
                    <View>
                        <Text style={styles.text}> {item.title} </Text> // use `title` here like this
                        <Switch    
                            .....
                            value={item.isEnable || false} // change here
                            onValueChange={(value) => toggleSwitch(value, index) } // change here
                        />
                    </View>
                )
            } 
            
            return (
                <>
                <View style = {styles.container}>
                    <FlatList
                        data = {data}
                        keyExtractor = {item => item.id}
                        renderItem = {({ item, index }) => <Item item={item} index={index} /> } // send `item` as prop
                    />
    
                </View>    
                </>
            
            );
        }
    

    【讨论】:

      【解决方案3】:

      这样做:

      const Item = ({ data }) => {
        const [isSwitchEnabled, toggleSwitch] = React.useState(data.switch)
      
        return (
          <View>
            <Text style={styles.text}> {data.title} </Text>
            <Switch
              onValueChange={() => toggleSwitch(!isSwitchEnabled)}
              trackColor={{ false: "#767577", true: "#81b0ff" }}
              thumbColor="#f5dd4b"
              ios_backgroundColor="#3e3e3e"
              value={isSwitchEnabled}
            />
          </View>
        )
      }
      
      export default () => {
        const DATA = [
          {
            id: '1',
            title: 'Toggle Night Mode',
            switch: false
          },
          {
            id: '2',
            title: 'Remind me to take a break',
            switch: false
          },
          {
            id: '3',
            title: "Remind me when it's bedtime",
            switch: false
          },
      
        ];
      
      
        function Header() {
          return (
            <View style={styles.header}>
              <Text style={styles.headertext}>Settings</Text>
            </View>
          )
        }
      
        return (
          <>
            <View>
              <SafeAreaView>
                <FlatList
                  data={DATA}
                  keyExtractor={item => item.id}
                  renderItem={({ item }) => <Item data={item} />}
                  ListHeaderComponent={Header()}
                  contentContainerStyle={styles.container}
                />
              </SafeAreaView>
            </View>
            <View>
              <Button
                title="Clear Search History"
                color="#6fb6f0"
                onPress={() => Alert.alert('Food History Has Been Cleared!')}
              />
            </View>
            <View>
              <Button
                title="Logout"
                color="#6fb6f0"
                onPress={() => Alert.alert('Successfully Logged Out!')}
              />
            </View>
      
          </>
      
        );
      }

      【讨论】:

        猜你喜欢
        • 2017-11-21
        • 2020-10-04
        • 1970-01-01
        • 2022-01-09
        • 1970-01-01
        • 1970-01-01
        • 2020-09-27
        • 2013-03-05
        • 2011-03-01
        相关资源
        最近更新 更多