Reactjs 我可以在React中返回条件语句吗?
我想在device==“Mobile”时隐藏输入元素,但我需要刷新页面才能看到效果,为什么Reactjs 我可以在React中返回条件语句吗?,reactjs,Reactjs,我想在device==“Mobile”时隐藏输入元素,但我需要刷新页面才能看到效果,为什么 export default function Input() { const [device,setDevice]=useState(""); function setDeviceWidth(width){ if(width>567){ return setDevice("noMobile"); } else{
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之后,您错过了依赖项数组…-)