【问题标题】:How does styling work in Material UI to change the color of the focus label?Material UI 中的样式如何改变焦点标签的颜色?
【发布时间】:2019-03-21 18:07:26
【问题描述】:

我正在尝试学习如何使用 JSS 进行样式设置。我想在 InputLabel 聚焦时更改标签的颜色。我最终让它在下面的代码中工作,但我不明白它为什么工作:

import React from 'react'
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles'
import { FormControl, InputLabel, Select, } from '@material-ui/core/'

const styles = theme => ({
  inputLabel: {
    '&$focused': {
      color: 'red',
    },
  },
  focused: {
  },
})

class Test extends React.Component {

  render() {
    const { classes } = this.props;

    return(
      <div>
        <FormControl>
          <InputLabel className={classes.inputLabel} FormLabelClasses={ classes }>Select</InputLabel>
          <Select/>
        </FormControl>
      </div>
    )
  }
}

Test.propTypes = {
  classes: PropTypes.object.isRequired,
}

export default withStyles(styles)(Test)

具体来说,我不明白为什么我不能在外部 focused 字段中将颜色设置为红色。我也不确定我是否理解&amp;$focused 的作用——我认为只是引用外部focused 字段,但如果是这样,为什么我不能将外部focused 字段设置为{ color: 'red' }?我试过了,但它不起作用。此外,如果我只是删除外部 focused 字段,它会停止将颜色设置为红色!为什么有必要?我也不明白将classes 传递给FormLabelClasses 的意义何在——如果我再次删除它,它不会导致焦点标签变红。

【问题讨论】:

    标签: css reactjs material-ui jss


    【解决方案1】:

    InputLabelFormLabel 的控制器包装器。它从FormControl 读取上下文以根据使用的变体应用样式。它使用classes 来实现额外的样式逻辑。这就是为什么您必须明确传递仅适用于 FormLabel 的类。

    要回答为什么不能简单地将颜色应用于focused 的问题,请阅读https://material-ui.com/customization/overrides/#overriding-with-classes 下的“内部状态”。

    您必须使用一个空对象来定义它,以便 JSS 将其作为类名来选择并允许对该规则的嵌套引用。链接部分也对此进行了说明。

    希望能充分回答所有问题。如果文档不清楚,您可以随时打开问题或在https://github.com/mui-org/material-ui 提交 PR。

    【讨论】:

    • 我不想向您重复您无法仅从实际源代码中读取的每个实现细节。如果您仍然对如何简化 API 有任何建议,请随时提出问题。焦点是浏览器设置的。它不应该被控制。
    猜你喜欢
    • 2020-07-08
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    • 2018-12-02
    • 2019-11-07
    • 1970-01-01
    • 2021-08-01
    相关资源
    最近更新 更多