2016-09-28 37 views
2

我試圖顯示一個組件,具體取決於哪個按鈕被點擊,但有這條線的問題。Reactjs - 給出錯誤的方法

{this.showTab({this.state.active})} 

它會拋出一個關於語法錯誤的錯誤。我做錯了什麼,有沒有更好的方式來顯示組件<Grids />,<Pics /><Maths />取決於我點擊。

import React, {Component} from 'react'; 
import Pics from './pics'; 
import Grids from './grids'; 
import Maths from './maths'; 
import { ButtonToolbar } from 'react-bootstrap'; 
import { Button } from 'react-bootstrap'; 



export default class Tabs extends Component { 
    constructor(props) { 
    super(); 
    this.state = { 
     count: 0, 
     active: null 
    }; 
    this.handleClick = this.handleClick.bind(this); 
    this.showTab = this.showTab.bind(this); 
    } 

    handleClick(value) { 
    this.setState({ 
     count: this.state.count + 1, 
     active: value 
    }); 
    } 

    showTab(tab) { 
    switch(tab) { 
     case "Grids": 
     return "<Grids />"; 
     break; 
     case "Pics": 
     return "<Pics />"; 
     break; 
     default: 
     return "<Maths />"; 
    } 
    } 

    render() { 
    return (
     <div> 
     <ButtonToolbar> 
      {this.props.tabs.map(listValue => 
      <Button onClick={this.handleClick.bind(this, listValue)}> 
       {listValue} 
      </Button> 
     )} 
     </ButtonToolbar> 

     {this.showTab({this.state.active})} 



     </div> 
    ); 
    } 
} 
+1

擺脫圍繞'this.state.active'的括號。 – Li357

+0

感謝 - 它的工作 - 但現在它只顯示「」,而不是呈現它。我將如何解決這個問題?我會更新上面的問題。 – Wasteland

+1

因爲你返回一個字符串。只要在案件中返回'。 – Li357

回答

2

這是你想要什麼:

import React, {Component} from 'react'; 
import Pics from './pics'; 
import Grids from './grids'; 
import Maths from './maths'; 
import { ButtonToolbar } from 'react-bootstrap'; 
import { Button } from 'react-bootstrap'; 

export default class Tabs extends Component { 
    constructor() { 
    super(); 
    this.state = { 
     count: 0, 
     active: null 
    }; 
    this.handleClick = this.handleClick.bind(this); 
    this.showTab = this.showTab.bind(this); 
    } 

    handleClick(value) { 
    this.setState({ 
     count: this.state.count + 1, 
     active: value 
    }); 
    } 

    showTab(tab) { 
    switch (tab) { 
     case 'Grids': 
     return <Grids />; 
     case 'Pics': 
     return <Pics />; 
     default: 
     return <Maths />; 
    } 
    } 

    render() { 
    const { tabs } = this.props; 
    const { active } = this.state; 
    return (
     <div> 
     <ButtonToolbar> 
      {tabs.map(listValue => 
      <Button onClick={() => this.handleClick(listValue)}> 
       {listValue} 
      </Button> 
     )} 
     </ButtonToolbar> 
     {this.showTab(active)} 
     </div> 
    ); 
    } 
} 

注意解構賦值如何保持你的組件易於閱讀。示例const { tabs } = this.props;請注意,我使用單引號代替""組件標記不需要引號。看看我們如何使用onClick的箭頭函數。因爲你已經綁定在構造函數中的onClick不實際的點擊再次綁定它...希望我的例子幫你

+0

非常感謝。 – Wasteland