简体   繁体   English

Reactjs中CSS className的类vs样式

[英]classes vs styles for CSS className in Reactjs

In the below code, why does a call to the classes object work? 在下面的代码中,为什么对classes对象的调用有效? It seems like the call should be to the styles object defined as a const up top. 看起来调用应该是定义为const up top的styles对象。

For example, in this demo : 例如, 在此演示中

className={classes.button}

works as written. 像书面一样工作。 But it seems like it should be 但它似乎应该是

className={styles.button}

Is there any actual classes object defined anywhere? 是否在任何地方定义了实际的classes对象? If so, where is it defined? 如果是这样,它在哪里定义? The markup implies a this.props.classes object. 标记意味着this.props.classes对象。 But there are no props passed to <Demo /> when called in index.js. 但是在index.js中调用时没有传递给<Demo /> props

What's going on here? 这里发生了什么?

https://codesandbox.io/s/qxv466wlq https://codesandbox.io/s/qxv466wlq
 import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from '@material-ui/core/styles'; import Button from '@material-ui/core/Button'; const styles = theme => ({ button: { margin: theme.spacing.unit, }, input: { display: 'none', }, }); function OutlinedButtons(props) { const { classes } = props; return ( <div> <Button variant="outlined" className={classes.button}> Default </Button> <Button variant="outlined" color="primary" className={classes.button}> Primary </Button> <Button variant="outlined" color="secondary" className={classes.button}> Secondary </Button> <Button variant="outlined" disabled className={classes.button}> Disabled </Button> <Button variant="outlined" href="#outlined-buttons" className={classes.button}> Link </Button> <input accept="image/*" className={classes.input} id="outlined-button-file" multiple type="file" /> <label htmlFor="outlined-button-file"> <Button variant="outlined" component="span" className={classes.button}> Upload </Button> </label> </div> ); } OutlinedButtons.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(OutlinedButtons); 

If you look at this line: 如果你看这一行:

export default withStyles(styles)(OutlinedButtons);

the answer to your question is provided I believe. 我相信你提出的问题的答案。 Material UI has a function withStyles that takes a styles object, and then returns another function that takes a component to return a new component. Material UI有一个函数withStyles ,它接受一个样式对象,然后返回另一个函数,该函数使一个组件返回一个新组件。 This is a Higher Order Component, and can be read about on the React docs. 这是一个高阶组件,可以在React文档中阅读

If you look at the linked code of withStyles , you can see the following line where it renders the passed in component: 如果查看withStyles的链接代码,可以看到它呈现传入组件的以下行:

return <Component {...more} classes={this.getClasses()} ref={innerRef} />;

And is providing the classes prop, making it available to any component exported with withStyles . 并提供classes prop,使其可用于使用withStyles导出的任何组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM