react material-ui框架中的类名约定

时间:2018-01-09 04:29:21

标签: reactjs material-ui

材料ui库中是否使用了类名约定?我目前正在使用material-ui-next。我注意到类名如" MuiFormControl-root-124"在附近有类名的数字的地方。对于Paper元素" MuiPaper-root-18 MuiPaper-shadow2-22 MuiPaper-rounded-19"。我在这里看不到一个模式。

是否有我缺席的约定。如果它像Bootstraps网格类一样有意义,那么理解这个框架会更容易。所有人都非常感谢。谢谢。

1 个答案:

答案 0 :(得分:3)

在material-ui v1中,类名在运行时是非确定性生成的,因此没有您应该遵守的约定。这说明了文档中的here

  

您可能已经注意到我们的样式解决方案生成的类名称是非确定性的,因此您无法依赖它们保持不变。

然而,这并不重要,因为您不应该首先使用原始CSS类名。相反,您使用withStyles为每个组件设置适当的样式:

import { withStyles } from 'material-ui/styles';

// Define the CSS styles you which to apply to your component
const styles = {
  root: {
    backgroundColor: 'red',
  },
};

class MyComponent extends React.Component {
  render () {
    // withStyles automatically provides the classes prop, which
    // will contain the generated CSS class name that you can match
    // to your component
    return <div className={this.props.classes.root} />;
  }
}

export default withStyles(styles)(MyComponent);

这些非确定性类名具有技术优势,包括改进的性能:

  

由于我们的类名称具有非确定性,我们可以实现开发和生产的优化。它们易于在开发中进行调试,并且在生产中尽可能短。

你应该注意到这种情况发生是因为material-ui采用了与Bootstrap这样的库相比完全不同的样式方法。虽然Bootstrap有一个CSS库,其中定义的类名应用于每个元素,但是材料-ui使用CSS in JS来注入样式。这允许在每个组件的JavaScript定义旁边定义和存储CSS。