How to change tabs width in material UI

こ雲淡風輕ζ 提交于 2019-12-06 01:26:29

If you want tabs of fixed width, you need to override the root css class passed to the Tab component, where you have to override both the minWidth and width attributes.

Example:

const Component = ({ classes }) => (
    <Tabs value={0}>
        <Tab classes={{ root: classes.tab }} label="One" />
        <Tab classes={{ root: classes.tab }} label="Two" />
    </Tabs>
);


// this is injected as classes prop into the wrapping component
const styles = {
    tab: {
        minWidth: 200, // a number of your choice
        width: 200, // a number of your choice
    }
};
export default withStyles(styles)(Component);

You're going to have to hardcode a tab width:

const width = 200;

const widthModifier = {
  width: `${width}px`,
};

And then apply it to change the tab width:

<Tab label="Item One" style={widthModifier}>

You're also going to have to keep track of the current active tab using onActive and calculate the displacement of the ink bar yourself. Here's a full working example:

import React, { Component } from 'react';
import {Tabs, Tab} from 'material-ui/Tabs';

const styles = {
  headline: {
    fontSize: 24,
    paddingTop: 16,
    marginBottom: 12,
    fontWeight: 400,
  },
};

const width = 200;

const widthModifier = {
  width: `${width}px`,
};

class TabWidth extends Component {
  constructor(props) {
    super(props);

    this.state = { selectedIndex: 0 };
  }

  render() {
    const { selectedIndex } = this.state;

    // Notice that I have to calculate the left position of the ink bar here for things to look right
    return (
      <Tabs inkBarStyle={ {left: `${width * selectedIndex}px`, ...widthModifier}}>
        <Tab label="Item One" style={widthModifier} onActive={() => this.setState({ selectedIndex: 0 })}>
          <div>
            <h2 style={styles.headline}>Tab One</h2>
            <p>
              You can put any sort of HTML or react component in here. It even keeps the component state!
            </p>
          </div>
        </Tab>
        <Tab label="Item Two" style={widthModifier} onActive={() => this.setState({ selectedIndex: 1 })}>
          <div>
            <h2 style={styles.headline}>Tab Two</h2>
            <p>
              This is another example tab.
            </p>
          </div>
        </Tab>
      </Tabs>
      );
    }
}

export default TabWidth;

But, you really should be using v1 if possible. In material-ui v1, your desired tab behavior is the default right out of the box and will scale based on screen size.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!