2016-09-28 39 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