为 TextField 中的占位符设置样式

新手上路,请多包涵

TextField API 没有提及如何设置输入元素的伪占位符元素的样式。

基本上,我想更改占位符文本的默认样式,并且 正常的技巧包 不起作用,因为我无法访问该元素。

有什么办法可以做到吗?如果是这样,JSS/React/DOM 的等效编写方式是什么 ::-webkit-input-placeholder

原文由 oligofren 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 423
1 个回答

情况1

Put the desired placeholder text in the label property of the TextField component, and use the labelClassName property of the TextField to customize it. You could also pass InputLabelProps with a className , classes or style attribute.

案例二

避免使用 label 属性, TextField 将占位符文本放在其 placeholder 属性上。利用 InputProps 覆盖生成的 HTML input 元素的类。

代码

下面的代码涵盖了上述两种情况。 代码沙盒片段

 import React from 'react';
import TextField from 'material-ui/TextField';
import { withStyles } from 'material-ui/styles';
import withRoot from '../components/withRoot';

const styles = {
  'input-label': {
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
    overflow: 'hidden',
    width: '100%',
    color: 'red'
  },

  'input': {
    '&::placeholder': {
      textOverflow: 'ellipsis !important',
      color: 'blue'
    }
  }
};

class Index extends React.Component {
  render() {
    return <div style={ {width: 150, margin: '0 auto'} }>
      {/* Uses "label" and "labelClassName". */}
      <TextField
        fullWidth
        label='I am a really really long red TextField label'
        labelClassName={ this.props.classes['input-label'] } />

      {/* Uses "label" and "InputLabelProps" with inline styles. */}
      <TextField
        fullWidth
        label='I am a really really long green TextField label'
        InputLabelProps={{
          style: {
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            width: '100%',
            color: 'green'
          } }} />

      {/* Uses "placeholder" and "InputProps" with "classes". */}
      <TextField
        fullWidth
        margin='normal'
        placeholder='I am a really really long glue TextField label'
        InputProps={{ classes: {input: this.props.classes['input']} }} />
    </div>;
  }
}

export default withStyles(styles)(Index);

编辑

如果您想要个性化特定的组件实例,那么前面的解决方案是不错的选择。要全局更改占位符,请参阅 ninjaPixel 的回答

原文由 Rafa Viotti 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏