Material-ui v1 Input focus style override

可紊 提交于 2021-01-23 01:45:15

问题


I'm trying to override the styling of the Input component when it is on focus via class name overide.

I have tried the following:

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

Thank you


回答1:


The best way to accomplish that is to override the focused style exposed by the Input component, but using classes instead of class names.

To do so, you should first create a CSS style class specifically for the focused 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",
  },
});

Then override the focused style on the Input like this:

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

When you join that all together, a full working example would look like this:

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

You can read more about overriding a component's styles with classes here.



来源:https://stackoverflow.com/questions/49040092/material-ui-v1-input-focus-style-override

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!