Material-ui v1 输入焦点样式覆盖

IT技术 reactjs material-ui
2021-05-10 09:03:07

当 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);

谢谢

1个回答

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

为此,您应该首先专门为焦点输入创建一个 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",
  },
});

然后像这样覆盖focused样式Input

<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);

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