首页 > 解决方案 > 在 React 中响应式地隐藏元素

问题描述

我正在使用 Reactstrap ,并且想在设备移动时隐藏我的输入元素。我使用的 className 与我们在 bootstrap 中使用的相同,但是 className 根本不起作用。有什么方法可以像 reactstap 中的 bootstrap 那样做?

 <input className="d-sm-none d-md-block" type="text"placeholder="Search"/>

我试过上面的代码来隐藏它,但它不起作用,有什么办法吗?

标签: reactjsreactstrap

解决方案


在正在呈现输入的父组件中;

这是假设您有功能性反应组件。相同的逻辑可以应用于 Class 组件。

  useEffect(() => {

    setDeviceWidth(window.innerWidth);

  const setDeviceWidth = width => {
    if (width < 767) {
      return setDevice("mobile");
    } else if (width > 767 && width < 1280) {
      return setDevice("tablet");
    }
    return setDevice("desktop");
  };

  }, []);

管理状态

const [device,setDevice]=useState("")

有条件地渲染输入

{device==="mobile"?null:<input/>}

推荐阅读