Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 我可以在React中返回条件语句吗?_Reactjs - Fatal编程技术网

Reactjs 我可以在React中返回条件语句吗?

Reactjs 我可以在React中返回条件语句吗?,reactjs,Reactjs,我想在device==“Mobile”时隐藏输入元素,但我需要刷新页面才能看到效果,为什么 export default function Input() { const [device,setDevice]=useState(""); function setDeviceWidth(width){ if(width>567){ return setDevice("noMobile"); } else{

我想在device==“Mobile”时隐藏输入元素,但我需要刷新页面才能看到效果,为什么

export default function Input() {
const [device,setDevice]=useState("");
function setDeviceWidth(width){
    if(width>567){
        return setDevice("noMobile");
    }
    else{
        return setDevice("Mobile");
    }
}  

useEffect(()=>{
    setDeviceWidth(window.innerWidth);
  
})
     
    
 return(
<div>
    {device==="Mobile"?<div></div>:<input type="text"/>}
</div>
 )
}
导出默认函数输入(){
const[device,setDevice]=useState(“”);
功能设置设备宽度(宽度){
如果(宽度>567){
返回设置设备(“noMobile”);
}
否则{
返回设置设备(“移动设备”);
}
}  
useffect(()=>{
setDeviceWidth(window.innerWidth);
})
返回(
{device==“Mobile”?:}
)
}

您的组件仅在安装时读取窗口宽度。 我建议您收听“调整窗口大小”事件:

    useEffect(() => {
        const listener = () => setDeviceWidth(window.innerWidth); // keep a reference to the listener
        window.addEventListener("resize", listener); // attach it to the resize event
        return () => window.removeEventListener("resize", listener); // detach it on unmounting
    }, []); // only run on mounting and unmounting

您的组件仅在安装时读取窗口宽度。 我建议您收听“调整窗口大小”事件:

    useEffect(() => {
        const listener = () => setDeviceWidth(window.innerWidth); // keep a reference to the listener
        window.addEventListener("resize", listener); // attach it to the resize event
        return () => window.removeEventListener("resize", listener); // detach it on unmounting
    }, []); // only run on mounting and unmounting

Mobile
不等于
Mobile
,请尝试使用
device==“Mobile”
。可能只是输入错误。我需要如何刷新页面才能看到效果,为什么?因为useEffect正好在组件重新加载后运行。调整窗口大小不会重新运行效果。我应该怎么做?在UseEffect之后您错过了依赖项数组…:)
Mobile
不等于
Mobile
,请尝试使用
device==“Mobile”
。可能只是输入错误。我需要如何刷新页面才能看到效果,为什么?因为useEffect正好在组件重新加载后运行。调整窗口大小不会重新运行效果。我应该怎么做?在UseEffect之后,您错过了依赖项数组…-)