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

doe*_*ute 1 javascript reactjs

我试图弄清楚如何在移动视图中以不同的方式呈现组件(我希望它在移动设备中显示在我的标题之前,但在其他情况下)

我现在的代码是

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}
    );
  }

}
Run Code Online (Sandbox Code Playgroud)

然而,这不起作用(组件未定义),我想我不能只将组件设置为字符串,但希望这是足够的信息,以正确的方式做任何建议

谢谢!

mad*_*ox2 7

您的代码有几个问题,请参阅注释以获取更多详细信息

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;
  }

}
Run Code Online (Sandbox Code Playgroud)

此外,我将此逻辑移动到render方法,不要使用state来存储组件,而是直接渲染它.例如:

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>
       );
     }
  }

}
Run Code Online (Sandbox Code Playgroud)