草庐IT

javascript - 在没有 CSS 的情况下 react 响应式布局

coder 2023-07-06 原文

我想知道在 React 应用程序中实现布局的最佳方法是什么。

基础知识

假设我们想要在简单的网格中布置 4 个组件。最基本的方法是这样的。

<svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
  <A color="red" x={0} y={0} width={width/2} height={height/2} />
  <B color="blue" x={width/2} y={0} width={width/2} height={height/2} />
  <B color="green" x={0} y={height/2} width={width/2} height={height/2} />
  <A color="yellow" x={width/2} y={height/2} width={width/2} height={height/2} />
</svg>

http://codepen.io/anon/pen/OWOXvV?editors=0010

它会很好地工作,但是键入明确的大小值很容易出错并且对开发人员不友好。如果我们可以改用百分比值 (0 - 1) 会怎么样?

简单容器

const Container = ({x, y, width, height, children}) => {
  return (
    <g transform={`translate(${x}, ${y})`}>
      {React.Children.map(children, (child) => React.cloneElement(child, { // this creates a copy
        x: child.props.x * width,
        y: child.props.y * height,
        width: child.props.width * width,
        height: child.props.height * height
      }))}
    </g>
  );
};

 <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
  <Container width={width} height={height}>{/* one root container is given real pixel size */}
    <Container width={1/2}>{/* it's children recursively use 0-1 coordinates */}
      <A color="red" height={1/2} />
      <B color="green" y={1/2} height={1/2} />
    </Container>
    <Container x={1/2} width={1/2}>
      <B color="blue" height={1/2} />
      <A color="yellow" y={1/2} height={1/2} />
    </Container>
  </Container>
</svg>

http://codepen.io/anon/pen/PWEmVd?editors=0010

在这种情况下,我们将允许容器组件将其子组件的相对值映射到实际像素值。它更易于使用。

布局容器

另一个步骤是创建布局容器,f.e. HContainer 简单地水平放置其子项。

const HContainer = ({ x, y, width, height, children }) => {
  const c = React.Children.toArray(children);
  const ratio = width / c.reduce((sum, child) => (sum + child.props.width), 0);
  return (
    <g transform={`translate(${x}, ${y})`}>
      {c.reduce((result, child) => {
        const width = child.props.width * ratio;
        result.children.push(React.cloneElement(child, { // this creates a copy
          x: result.x,
          y: 0,
          width,
          height
        }));
        result.x += width;
        return result;
      }, { x: 0, children: [] }).children}
    </g>
  );
};

<svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
  <HContainer width={width} height={height}>{/* one root container is given real pixel size */}
    <Container width={1/4}>{/* it's children recursively use 0-1 coordinates */}
      <A color="red" height={1/2} />
      <B color="green" y={1/2} height={1/2} />
    </Container>
    <VContainer width={3/4}>
      <B color="blue" />
      <A color="yellow" />
      <HContainer height={1/2}>
        <B color="pink" />
        <A color="violet" width={3} />
        <B color="#333" />
      </HContainer>
    </VContainer>
  </HContainer>
</svg>

http://codepen.io/anon/pen/pRpwBe?editors=0010

响应式组件

假设我们希望在宽度或高度低于某个值时删除某些组件。您可能会像这样使用条件渲染。

const MinWidth = ({ children, width, minWidth, ... others }) => {
  return minWidth > width ? null : <Container width={width} {... others }>{ children }</Container>;
};

<svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
  <HContainer width={width} height={height}>{/* one root container is given real pixel size */}
    <Container width={1/4}>{/* it's children recursively use 0-1 coordinates */}
      <A color="red" height={1/2} />
      <B color="green" y={1/2} height={1/2} />
    </Container>
    <VContainer width={3/4}>
      <B color="blue" />
      <MinHeight height={1} minHeight={80}>
        <A color="yellow" />
      </MinHeight>
      <HContainer height={1/2}>
        <B color="pink" />
        <A color="violet" width={3} />
        <MinWidth width={1} minWidth={60}>
          <B color="#333" />
        </MinWidth>
      </HContainer>
    </VContainer>
  </HContainer>
</svg>

http://codepen.io/anon/pen/dNJZGd?editors=0010

但这会在过去被跳过的组件所在的地方留下空白。布局容器应该能够扩展呈现的组件以填充可用空间。

响应式布局

这是棘手的部分。我看不出有其他方法可以查看组件是否会呈现,而是实例化和呈现它(及其子组件)。然后,如果我在可用空间内放置 3 个子组件并发现不应渲染第 4 个,我将不得不重新渲染前 3 个。感觉就像打破了 React 流程。

有没有人有什么想法?

最佳答案

在内联样式中使用 flexbox。从代码的外观来看,您已经在使用内联样式。 Here is some help

关于javascript - 在没有 CSS 的情况下 react 响应式布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41961900/

有关javascript - 在没有 CSS 的情况下 react 响应式布局的更多相关文章

  1. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  2. ruby - capybara field.has_css?匹配器 - 2

    我在MiniTest::Spec和Capybara中使用以下规范:find_field('Email').must_have_css('[autofocus]')检查名为“电子邮件”的字段是否具有autofocus属性。doc说如下:has_css?(path,options={})ChecksifagivenCSSselectorisonthepageorcurrentnode.据我了解,字段“Email”是一个节点,因此调用must_have_css绝对有效!我做错了什么? 最佳答案 通过JonasNicklas得到了答案:No

  3. ruby-on-rails - rails 目前在重启后没有安装 - 2

    我有一个奇怪的问题:我在rvm上安装了ruby​​onrails。一切正常,我可以创建项目。但是在我输入“railsnew”时重新启动后,我有“程序'rails'当前未安装。”。SystemUbuntu12.04ruby-v"1.9.3p194"gemlistactionmailer(3.2.5)actionpack(3.2.5)activemodel(3.2.5)activerecord(3.2.5)activeresource(3.2.5)activesupport(3.2.5)arel(3.0.2)builder(3.0.0)bundler(1.1.4)coffee-rails(

  4. ruby - 默认情况下使选项为 false - 2

    这是在Ruby中设置默认值的常用方法:classQuietByDefaultdefinitialize(opts={})@verbose=opts[:verbose]endend这是一个容易落入的陷阱:classVerboseNoMatterWhatdefinitialize(opts={})@verbose=opts[:verbose]||trueendend正确的做法是:classVerboseByDefaultdefinitialize(opts={})@verbose=opts.include?(:verbose)?opts[:verbose]:trueendend编写Verb

  5. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  6. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

  7. 没有类的 Ruby 方法? - 2

    大家好!我想知道Ruby中未使用语法ClassName.method_name调用的方法是如何工作的。我头脑中的一些是puts、print、gets、chomp。可以在不使用点运算符的情况下调用这些方法。为什么是这样?他们来自哪里?我怎样才能看到这些方法的完整列表? 最佳答案 Kernel中的所有方法都可用于Object类的所有对象或从Object派生的任何类。您可以使用Kernel.instance_methods列出它们。 关于没有类的Ruby方法?,我们在StackOverflow

  8. ruby - nanoc 和多种布局 - 2

    是否可以为特定(或所有)项目使用多个布局?例如,我有几个项目,我想对其应用两种不同的布局。一个是绿色的,一个是蓝色的(但是)。我想将它们编译到我的输出目录中的两个不同文件夹中(例如v1和v2)。我一直在玩弄规则和编译block,但我不知道这是怎么回事。因为,每个项目在编译过程中只编译一次,我不能告诉nanoc第一次用layout1编译,第二次用layout2编译。我试过这样的东西,但它导致输出文件损坏。compile'*'doifitem.binary?#don’tfilterbinaryitemselsefilter:erblayout'layout1'layout'layout2'

  9. ruby - 在不使用 RVM 的情况下在 Mac 上卸载和升级 Ruby - 2

    我最近决定从我的系统中卸载RVM。在thispage提出的一些论点说服我:实际上,我的决定是,我根本不想担心Ruby的多个版本。我只想使用1.9.2-p290版本而不用担心其他任何事情。但是,当我在我的Mac上运行ruby--version时,它告诉我我的版本是1.8.7。我四处寻找如何简单地从我的Mac上卸载这个Ruby,但奇怪的是我没有找到任何东西。似乎唯一想卸载Ruby的人运行linux,而使用Mac的每个人都推荐RVM。如何从我的Mac上卸载Ruby1.8.7?我想升级到1.9.2-p290版本,并且我希望我的系统上只有一个版本。 最佳答案

  10. ruby-on-rails - Rails 3,嵌套资源,没有路由匹配 [PUT] - 2

    我真的为这个而疯狂。我一直在搜索答案并尝试我找到的所有内容,包括相关问题和stackoverflow上的答案,但仍然无法正常工作。我正在使用嵌套资源,但无法使表单正常工作。我总是遇到错误,例如没有路线匹配[PUT]"/galleries/1/photos"表格在这里:/galleries/1/photos/1/edit路线.rbresources:galleriesdoresources:photosendresources:galleriesresources:photos照片Controller.rbdefnew@gallery=Gallery.find(params[:galle

随机推荐