首页 > 解决方案 > Reactjs 没有按预期呈现条件输出

问题描述

我已经发布了一个关于我的问题的问题,但这仍然没有解决:

Reactjs 袜子不会将向下模式应用于渲染输出

我有以下代码(请向下滚动到同一底部):

import React from "react";
import { setDefaultBreakpoints } from "react-socks";
import Breakpoint, { BreakpointProvider } from "react-socks";

class BreakpointComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  componentWillMount() {
    setDefaultBreakpoints([{ mobile: 900 }]);
  }

  render() {
    return (
      <BreakpointProvider>
        <Breakpoint mobile down>
          <MobileComponent />
        </Breakpoint>

        <Breakpoint mobile up>
          <DesktopComponent />
        </Breakpoint>
      </BreakpointProvider>
    );
  }
}

class DesktopComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <h1>I WILL RENDER ON DESKTOP</h1>
      </div>
    );
  }
}

class MobileComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <div>
        <h1>I WILL RENDER ON MOBILE</h1>
      </div>
    );
  }
}

export default BreakpointComponent;

我获得以下输出:

这不是我所期望的。

也许我有问题,因为 React Socks 与 React Router 不兼容。这就是我将它放在 App.js React 根文件中的方式:

// ...
return (
  <BrowserRouter>
    <div>
      <Switch>
        <Route path="/breakpoint" render={props => <BreakpointComponent {...props} />} exact />
      </Switch>
    </div>
  </BrowserRouter>
);
// ...

我不想接收我想要的屏幕尺寸大于 900 像素的输出,以及我想要在当前屏幕尺寸小于 900 像素时接收的输出。

我错过了什么?

标签: javascriptreactjsresponsive-design

解决方案


我不太确定react-socks您使用的是哪个版本。但是根据最新的文档,您必须按如下方式使用它。

return (
<div>
  <Breakpoint small down>
    <div>I will render only in mobile devices</div>
  </Breakpoint>

  <Breakpoint medium only>
    <div>I will render only in tablets (iPad, etc...)</div>
  </Breakpoint>

  <Breakpoint medium down>
    <div>I will render in tablets (iPad, etc...) and everything below (mobile devices)</div>
  </Breakpoint>

  <Breakpoint medium up>
    <div>I will render in tablets (iPad, etc...) and everything above (laptops, desktops)</div>
  </Breakpoint>

  <Breakpoint large up>
    <div>I will render in laptops, desktops and everything above</div>
  </Breakpoint>
</div>);

您使用的是“移动”一词而不是关键字small,medium,large


推荐阅读