首页 > 解决方案 > React Native 视图不起作用,如果语句

问题描述

                onValueChange={(itemValue) => {
                    setSelectedValue(itemValue); 
                    if(itemValue == 'other'){
                        alert('You Choose: '+itemValue+' Nice')
                        
                        return(
                            // The <View> Doesnt Work Why ????
                            <View style={{backgroundColor:'red',height:5000,width:5000,}}>
                                <Text>Anas</Text>
                            </View>
                        )
                        
                    }
                    
                }}

不工作为什么????如果声明或我可以,我不能把它放进去?我不知道!

标签: androidiosreactjsreact-native

解决方案


我整理了一个小沙箱,您可以在其中看到如何实现您想要的示例:https ://codesandbox.io/s/sad-bird-lzzbb

import React, { useState } from "react";
import { Button, Text, View } from "react-native";

export default function App() {
  const [selectValue, setSelectedValue] = useState('');

  const onValueChange = (itemValue) => {
    setSelectedValue(itemValue);
  };

  return (
    <div className="App">
      <Button
        onPress={() => onValueChange("other")}
        title="Click to set value to 'other'"
      />
      {selectValue === "other" ? (
        <View style={{ backgroundColor: "red", height: 5000, width: 5000 }}>
          <Text>Anas</Text>
        </View>
      ) : null}
    </div>
  );
}

您可以使用该onValueChange函数在任何您想要的事件中将其作为回调传递(例如onPress我创建的那个按钮),但是您需要在返回功能组件时返回所有 jsx(或者render如果您正在使用类,则返回该函数组件)


推荐阅读