【问题标题】:Render div with state only on phones仅在手机上呈现带有状态的 div
【发布时间】:2022-01-16 08:31:48
【问题描述】:

有什么方法可以有条件地渲染 div 状态,但仅适用于手机? 我有显示更多按钮,但我只需要它用于电话分辨率,我还需要每次在桌面上显示带有 className 文本的 div

const ListItem = ({ text }) => {
    let [showMore, setShowMore] = useState(false);

    return (
        <div className="item">
            <div>
                <div className={`text ${showMore ? "active" : ""}`}>{text}</div>
            </div>
            <button onClick={() => setShowMore((s) => !s)}>Show more</button>
        </div>
    );
};

【问题讨论】:

    标签: javascript html reactjs typescript


    【解决方案1】:

    您可以在媒体查询中设置活动类。

    起初,你可以让这个 div 不显示任何内容。当您的分辨率是电话时,您设置显示块。

    .active{
            display: none;
        }
    
        @media screen and(max-widht: '400px') {
           .active{
                display: block;
           }
        }
    

    【讨论】:

      【解决方案2】:

      您可以使用纯 CSS 或使用挂钩进行媒体查询,如下所示:

      import {useMediaQuery, useMediaQueries} from '@react-hook/media-query'
       
      // Using a single media query
      const Component = () => {
        const matches = useMediaQuery('only screen and (min-width: 400px)')
        return `Matches? ${matches ? 'Matched!' : 'Nope :(')}`
      }
       
      // Using multiple media queries
      const Component = () => {
        const {matches, matchesAny, matchesAll} = useMediaQueries({
          screen: 'screen',
          width: '(min-width: 400px)'
        })
       
        return (
          <div>
            Screen matched? {matches.screen ? 'Yes' : 'No'}
            Width matched? {matches.width ? 'Yes' : 'No'}
            All matched? {matchesAll ? 'Yes' : 'No'}
            Any matched? {matchesAny ? 'Yes' : 'No'}
          </div>
        )
      }
      import {useMediaQuery, useMediaQueries} from '@react-hook/media-query'
        
      // Using multiple media queries
      const Component = () => {
        const {matches, matchesAny, matchesAll} = useMediaQueries({
          screen: 'screen',
          width: '(max-width: 767px)'
        })
       
        return (
          {matches.screen ? (<div>Display on mobile</div>) : ''}
        )
      }
      

      请注意,此解决方案依赖于this addon

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-29
        • 1970-01-01
        • 1970-01-01
        • 2016-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多