Reactjs - 给出错误的方法

时间:2016-09-28 22:10:41

标签: reactjs this

我正在尝试显示一个组件,具体取决于点击了哪个按钮但该行有问题。

{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 个答案:

答案 0 :(得分: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,所以在实际点击时不再绑定它...希望我的例子帮助你

相关问题