setState不能在本机反应中切换值

时间:2020-11-09 05:56:15

标签: reactjs react-native setstate

我具有切换状态变量值的功能。 状态变量的初始值为false

这是我的职能...

    expandLists(label){ // "label" is a state variable that passed as a string 
        let result = new Boolean();
        console.log(this.state);
        if(this.state.label){
            result=false;
            console.log('Result = false');
        }
        else{
            result=true;
            console.log('Result = true');
        }
        this.setState({[label]: result},console.log(this.state))
    }

在上述处于初始状态的表达式中,值更改为false,然后未更改为true

我也尝试过..以下方法...

    expandLists(label){
        this.setState( preState => ({label: !this.preState.label}),console.log(this.state))
    }

6 个答案:

答案 0 :(得分:0)

如果您将label参数作为字符串传递,请尝试以下操作:

    expandLists(label){ // "label" is a state variable that passed as a string 
        let result = new Boolean();
        console.log(this.state);
        if(this.state[label]){
            result=false;
            console.log('Result = false');
        }
        else{
            result=true;
            console.log('Result = true');
        }
        this.setState({[label]: result},console.log(this.state))
    }

所以区别在于检查当前值是否为 truethy 。代替使用this.state.label,而使用this.state[label]

答案 1 :(得分:0)

以这种方式检查您所说的字符串的“标签”参数类型

if(this.state.label == "true"){
...
}

if(this.state[label]){
...
}

答案 2 :(得分:0)

实现这一目标的简便方法是

toggleLabelValue = (label) => {
    this.setState({ [label]: !this.state[label] }, () =>
      console.log(this.state)
    );
};

答案 3 :(得分:0)

尝试以这种方式切换状态:

import React from 'react';

import {
    View,
    Button,
} from 'react-native';

export default class App extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            label: false
        }
    }

    changeLabel = (currentLabel) => {
        this.setState({
            label: currentLabel
        });
    };

    toggleLabel = () => {
        this.changeLabel(!this.state.label);
    };

    render() {
        return (
            <View>
                <Button onPress={this.toggleLabel} title="Toggle Label" />
            </View>
        );
    }

}

答案 4 :(得分:0)

这里是使用钩子的另一种实现方式:

import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';

export default function App() {
  const [label, setLabel] = useState(false);
  const toggleLable = () => {
    let temp = label;
    setLabel(!temp);
  };
  return (
    <View style={styles.container}>
      <TouchableOpacity
        onPress={toggleLable}
        style={[
          styles.btn,
          { backgroundColor: label ? '#4f4' : '#f40' },
        ]}>
        <Text style={styles.text}>{label? "TRUE": "FALSE"}</Text>
        </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  btn: {
    width: 200,
    height: 200,
    borderRadius: 20,
    justifyContent: "center"
  },
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
    alignItems: 'center',
  },
  text:{
    fontSize: 40,
    fontWeight: "bold",
    color: "white",
    textAlign: "center"
  }
});


屏幕截图:

enter image description here

您可以在此处使用以下代码:Toggle Button Example

答案 5 :(得分:0)

这对我使用 useState 有效:

import React, { useState } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import SeparateModal from 'components/SeparateModal';

export default function Parent() { 
  const [modalVisible, setModalVisible] = useState(false);

  return (
    <View>

      <SeparateModal 
        modalVisible={modalVisible}
        setModalVisible = {setModalVisible}
      />

      <TouchableOpacity>
        <Text onPress = { () => setModalVisible(true) }>Open Modal</Text>
      </TouchableOpacity>

    </View>
  )
}

组件/SeparateModal:

export default function SeparateModal({ modalVisible, setmodalVisible }) {
  return (
    <Modal 
      visible={ modalVisible }
      animationType="slide" 
    >
      <View>
        <TouchableOpacity>
          <Text onPress = { () => setModalVisible(false) }>Close Modal</Text>
        </TouchableOpacity>
      </View>
    </Modal>
  );