【问题标题】:(SemanticUI + React) Changing HTML elements based on screen size best approach?(语义 UI + React)根据屏幕大小更改 HTML 元素的最佳方法?
【发布时间】:2017-12-09 10:17:58
【问题描述】:

例如,假设我想在显示尺寸低于 600 像素宽度时删除图像。什么是最干净、最快和最易于维护的方法?

  <div class="card"> 
      <div class="image">
          <img src="http://placehold.it/256x256">
      </div> 

      <div class="content">
              <a class="header">Kristy</a>
          <div class="meta">
              <span class="date">Joined in 2013</span>
          </div>
          <div class="description">
              Kristy is an art director living in New York.
          </div>
      </div>
      <div class="extra content">
          <a>
              <i class="user icon"></i>
              22 Friends
          </a>
      </div>
  </div>

jQuery method

EDIT: Definitely not using jQuery (it works, but read below):

jQuery 免费

jQuery 是一个 DOM 操作库。它读取和写入 DOM。 React 使用虚拟 DOM(真实的 DOM)。 React 仅将补丁更新写入 DOM,但从不读取 它。

让真实的 DOM 操作与 React 的操作保持同步是不可行的 虚拟 DOM。正因为如此,所有的 jQuery 功能都已经 在 React 中重新实现。

<script>
  $(window).resize(function () {
     if (window.innerWidth < 600) { //Some arbitrary mobile width
        $(".image img").attr("src", "");
     } else {
        $(".image img").attr("src", "http://placehold.it/256x256");
     }
  });
</script>

SemanticUI method(Doc)

<div class="ui container desktop only grid">
  Contents
</div> 

Using React only?

  render() {
    let content = this.state.width < 600 ? <MobileComponent/> : <DesktopComponent />;
    return(<div>
        <div>{content}</div>
        <childComponent myWidth= {this.state.width}></childComponent >
        <childComponent2 myWidth= {this.state.width}></childComponent2 >
   </div>
  )

【问题讨论】:

  • 如果宽度低于给定值,CSS 媒体查询可以对图像应用无显示。
  • 绝对是 CSS 和一个类名系统,当屏幕宽度(或高度,尽管在我的经验中宽度更重要)低于(或高于)某个阈值时,允许元素被识别为隐藏.

标签: javascript jquery reactjs semantic-ui


【解决方案1】:

如果您的 GUI 在两个版本之间发生显着变化,则在适当的情况下维护两组组件可能是值得的。然后,您可以像这样渲染它们:

render() {
    // don't create the component here with <>, just choose which one to use
    let TheComponent = this.state.width < 600 ? MobileComponent : DesktopComponent;

    return (
        <div>
            <TheComponent prop1=... />
            ...
        </div>
    );
}

优点是您不会创建不需要的 DOM 节点,因此与纯 CSS 解决方案相比,性能可能会更好。而且,有时重新洗牌要容易得多。缺点显然是需要更多的代码。

【讨论】:

    【解决方案2】:

    使用媒体查询并附加到您的班级。例如

    HTML:

     <div class="image hideOnSmallScreen">
                  <img src="http://placehold.it/256x256">
              </div> 
    

    CSS:

    .image {
       display:block;
    }
    
    /* Small screens */
    @media all and (max-width: 700px) {
       .image.hideOnSmallScreen {
          display:none;
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-04
      • 2013-05-14
      • 2023-04-01
      • 2020-09-29
      • 1970-01-01
      • 2020-09-04
      • 1970-01-01
      相关资源
      最近更新 更多