2016-08-30 25 views
0

我想解決的是如何在移動視圖中以不同的方式渲染組件(我希望它在移動設備中顯示在我的標題之前,但在其他情況下)根據屏幕大小以不同的順序渲染組件(反應)

在一分鐘的代碼我已經是

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

} 

但是這不工作(沒有定義的組件),我想我不能只是設置組件爲字符串,但希望這是足夠的信息任何建議在正確的方式做到這一點

比KS!

回答

1

你的代碼中有幾個問題,詳細信息請參閱評論:

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

} 
+0

那裏有一些有用的信息,謝謝! –