Set text input placeholder color in reactjs

2019-03-30 10:20发布

问题:

When using ordinary CSS if you want to style your place holder you use these css selectors :

::-webkit-input-placeholder {
    color: red;
}

But I can't figure out how to apply these type of styles in react inline styles.

回答1:

You could try to use radium

var Radium = require('radium');
var React = require('react');
var color = require('color');

@Radium
class Button extends React.Component {
  static propTypes = {
    kind: React.PropTypes.oneOf(['primary', 'warning']).isRequired
  };

  render() {
    // Radium extends the style attribute to accept an array. It will merge
    // the styles in order. We use this feature here to apply the primary
    // or warning styles depending on the value of the `kind` prop. Since its
    // all just JavaScript, you can use whatever logic you want to decide which
    // styles are applied (props, state, context, etc).
    return (
      <button
        style={[
          styles.base,
          styles[this.props.kind]
        ]}>
        {this.props.children}
      </button>
    );
  }
}

// You can create your style objects dynamically or share them for
// every instance of the component.
var styles = {
  base: {
    color: '#fff',

    // Adding interactive state couldn't be easier! Add a special key to your
    // style object (:hover, :focus, :active, or @media) with the additional rules.
    ':hover': {
      background: color('#0074d9').lighten(0.2).hexString()
    },
    '::-webkit-input-placeholder' {
        color: red;
    }
  },

  primary: {
    background: '#0074D9'
  },

  warning: {
    background: '#FF4136'
  }
};


回答2:

You can't use ::-webkit-inline-placeholder inline.

It is a pseudo-element that (much like e.g. :hover) can only be used in your stylesheet:

The non-standard proprietary ::-webkit-input-placeholder pseudo-element represents the placeholder text of a form element.

Source

Instead, assign a class to the React component via the className property and apply the style to this class.



回答3:

For me, I use Radium's Style component. Here's what you can do in ES6 syntax:

import React, { Component } from 'react'
import Radium, { Style } from 'radium'

class Form extends Component {
   render() {
      return (<div>
         <Style scopeSelector='.myClass' rules={{
            '::-webkit-input-placeholder': {
               color: '#929498'
            }}} />
         <input className='myClass' type='text' placeholder='type here' />
      </div>
   }
}

export default Radium(Form)