是否可以将useState设置为变量?

时间:2019-09-23 19:14:41

标签: react-native variables state

对于使用react setState的功能组件,是否可以使用参数变量来更改状态的切换函数?

 const WhateverScreen = props => {
   const [showPieView, setShowPieView] = useState(false);
   const [showPizzaView, setShowPizzaView] = useState(false);
   const [showBurgerView, setShowBurgerView] = useState(false);

  const toggleView = (value) => {
      const stateData = "show" + value;
      const setStateData = "setShow" + value;
      if(stateData === true) {
         setStateData(false);
       } else {
        setStateData(true)
       };
      };

然后渲染:

 <TouchableOpacity onPress={() => {toggleView("Pizza")}} >
     <Ionicons name="ios-information-circle" size={40} color={"green"} />
  </TouchableOpacity>

 {showPizzaView ?
      <View >
        <Text>I like Pizza!!!</Text>
        <Image source={require("../images/pizza.jpg")} style= {height: 100, width: 100}/>
      </View> : null}
 }

我可以为每个Touchable元素编写一堆函数,但是然后DRY,对吗?

1 个答案:

答案 0 :(得分:0)

如果您真的要按名称访问每个函数,则可以将每个调度程序添加到一个对象中:

// rest of code
const [showPieView, setShowPieView] = useState(false);
const [showPizzaView, setShowPizzaView] = useState(false);
const [showBurgerView, setShowBurgerView] = useState(false);

const setShowView = {
  setShowPieView: setShowPieView,
  setShowPizzaView: setShowPizzaView,
  setShowBurgerView: setShowBurgerView
};
// rest of code

然后,您的setStateData将是const setStateData = setShowView["setShow" + value;],您的其余代码将按原样工作(PS:我没有测试过,主要是为了说明这个想法(^^,)。