javascript - 根据屏幕大小(React)以不同顺序渲染组件

标签 javascript reactjs

我正在尝试弄清楚如何在移动 View 中以不同方式呈现组件(我希望它出现在移动设备的标题之前,但否则出现在之后)

我现在的代码是

import React from 'react';
import NavigationBar from './NavigationBar';
import SiteHeader from './SiteHeader';

export default class App extends Component {

  constructor(props) {
     super(props);
     let width = window.innerWidth;
     if (width > 768) {
       this.setState(renderComponent =
         `<div className="container">
           <NavigationBar />
           <SiteHeader />
           {this.props.children}
         </div>`
       );
     } else {
       this.setState(renderComponent =
         `<div className="container">
           <NavigationBar />
           <SiteHeader />
           {this.props.children}
         </div>`
       );
     }
   }

  render() {

    return (
      {renderComponent}
    );
  }

}

但是这是行不通的(未定义组件),我想我不能只将组件设置为字符串,但希望这足以提供有关正确方法的任何建议

谢谢!

最佳答案

您的代码有几个问题,有关详细信息,请参阅评论:

export default class App extends Component {

  constructor(props) {
     super(props);
     // typo: use `=` instead of `:`
     let width = window.innerWidth;
     // dont use setState in constructor, initialize state instead
     this.state = {};
     if (width > 768) {
       // set renderComponent property according to window size
       // components are declared using JSX, not string (do not use ``)
       this.state.renderComponent = (
         <div className="container">
           <NavigationBar />
           <SiteHeader />
           {this.props.children}
         </div>
       );
     } else {
       this.state.renderComponent = (
         <div className="container">
           <NavigationBar />
           <SiteHeader />
           {this.props.children}
         </div>
       );
     }
   }

  render() {
    // access state through `this.state`
    // you don't need {} while it is not inside JSX
    return this.state.renderComponent;
  }

}

此外,我会将此逻辑移至渲染方法,不使用状态来存储组件而是直接渲染它。例如:

export default class App extends Component {

  render() {
     let width = window.innerWidth;
     if (width > 768) {
       return (
         <div className="container">
           <NavigationBar />
           <SiteHeader />
           {this.props.children}
         </div>
       );
     } else {
       return (
         <div className="container">
           <NavigationBar />
           <SiteHeader />
           {this.props.children}
         </div>
       );
     }
  }

}

关于javascript - 根据屏幕大小(React)以不同顺序渲染组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39235506/

相关文章:

javascript - 从指令添加到 dom 中的脚本未触发

php - 电子商务 : an intelligent shopping cart.

javascript - react - 组合功能

node.js - 'aws_amplify__WEBPACK_IMPORTED_MODULE_2___default.a.signUp 不是函数'

javascript - ReactJS:onMouseEnter 仅在单击时触发

reactjs - Material 表编辑/删除按钮更改操作

javascript - 如何优化我的 javascript 代码?

javascript - 来自youtube搜索的Ajax自动完成功能,跨域请求被阻止

javascript - 用于获取个人资料信息的 Chrome identity api

javascript - 尝试使用 React + TypeScript 项目修复 tslint 错误