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

Abh*_*iya 5 reactjs material-ui

Material ui 库中是否有类名约定?我目前正在使用material-ui-next。我注意到类名如“MuiFormControl-root-124”到处都是,类名后附有数字。对于纸元素“MuiPaper-root-18 MuiPaper-shadow2-22 MuiPaper-rounded-19”。我只是看不到这里的模式。

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

Jul*_*ont 6

在material-ui v1中,类名是在运行时不确定地生成的,因此没有您应该遵守的约定。文档中对此进行了描述:

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

不过,这并不重要,因为您一开始就不应该使用原始 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);
Run Code Online (Sandbox Code Playgroud)

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

由于类名的不确定性,我们可以实现开发和生产的优化。它们在开发过程中易于调试,并且在生产过程中的时间尽可能短。

您应该注意,发生这种情况是因为material-ui 采用与 Bootstrap 这样的库完全不同的方法来设计样式。虽然 Bootstrap 有一个 CSS 库,其中定义了应用于每个元素的类名,但 Material-ui在 JS 中使用 CSS来注入样式。这使得 CSS 可以与每个组件的 JavaScript 定义一起定义和存储。