【问题标题】:Material-ui v1 Input focus style overrideMaterial-ui v1 输入焦点样式覆盖
【发布时间】:2018-02-28 23:00:42
【问题描述】:

我正在尝试通过类名覆盖来覆盖 Input 组件的样式。

我尝试了以下方法:

const style = theme => ({
  input: {
    width: '20%',
    borderRadius: 4,
    backgroundColor: 'white',
    border: '1px solid #ced4da',
    fontSize: 20,
    '&:focus': {
      width: '40%',
      borderColor: '#80bdff',
      boxShadow: '0 0 0 0.2rem rgba(0,123,255,.25)',
    },
  }
});

class test extends Component {

// UI
render() {
    const {classes} = this.props
    return (
        <AppBar position="static">
            <Toolbar>
                <Input className={classes.input} />
            </Toolbar>
        </AppBar>
    );
}
}

export default withStyles(style)(test);

谢谢

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    实现这一点的最佳方法是覆盖Input 组件公开的focused 样式,但使用类而不是类名。

    为此,您应该首先专门为焦点输入创建一个 CSS 样式类:

    const styles = theme => ({
      input: {
        width: '20%',
        borderRadius: 4,
        backgroundColor: 'white',
        border: '1px solid #ced4da',
        fontSize: 20,
      },
      // Separate this part into it's own CSS class
      inputFocused: {
        width: '40%',
        borderColor: '#80bdff',
        boxShadow: '0 0 0 0.2rem rgba(0,123,255,.25)',
        backgroundColor: "#00FF00",
      },
    });
    

    然后像这样覆盖Input 上的focused 样式:

    <Input
      className={classes.input}
      classes={{ focused: classes.inputFocused}}
    />
    

    当您将所有这些结合在一起时,一个完整的工作示例将如下所示:

    import React from 'react';
    import PropTypes from 'prop-types';
    import { withStyles } from 'material-ui/styles';
    import Input from 'material-ui/Input';
    
    const styles = theme => ({
      input: {
        width: '20%',
        borderRadius: 4,
        backgroundColor: 'white',
        border: '1px solid #ced4da',
        fontSize: 20,
      },
      // Separate this part into it's own CSS class
      inputFocused: {
        width: '40%',
        borderColor: '#80bdff',
        boxShadow: '0 0 0 0.2rem rgba(0,123,255,.25)',
        backgroundColor: "#00FF00",
      },
    });
    
    function Inputs(props) {
      const { classes } = props;
      return (
        <div className={classes.container}>
          <Input
            className={classes.input}
            classes={{ focused: classes.inputFocused}}
          />
        </div>
      );
    }
    
    Inputs.propTypes = {
      classes: PropTypes.object.isRequired,
    };
    
    export default withStyles(styles)(Inputs);
    

    您可以阅读有关使用类here 覆盖组件样式的更多信息。

    【讨论】:

    • 愚蠢的问题,但这就是 中使用的 className 和 classes 之间的区别?
    • 类可以针对用于构建组件的特定元素
    猜你喜欢
    • 2020-01-30
    • 2019-03-07
    • 2020-05-27
    • 2020-08-10
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    • 1970-01-01
    相关资源
    最近更新 更多