在 React Native 中使用样式化组件更改 TextInput 占位符的颜色

Change the color of a TextInput placeholder with Styled Components in React Native

如何使用 React Native 中的 Styled Components 设置 TextInput 其 placeholder 的颜色]?

我尝试了以下但没有成功:

1.

const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

   ::placeholder {
       color: green;
   }
`

2.

const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

   &::placeholder {
       color: green;
   }
`

更改文本输入占位符文本颜色用户属性 "placeholderTextColor" 例如

<TextInput
        style={{height: 40, borderColor: 'gray', borderWidth: 1}}
        onChangeText={(text) => this.setState({text})}
        placeholder = 'Enter text'
        placeholderTextColor = 'red'
        value={this.state.text}
      />

您不能直接使用 styled-components 设置占位符颜色的样式,但您可以将 placeholderTextColor 属性 传递给设置样式的 Textinput。

示例:

const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

`

然后在渲染函数中:

<Input placeholder="hello" placeholderTextColor="green" />

输出:

工作示例:

https://snack.expo.io/rybp-nKaE

最好的制作方法:

export const Input = styled.TextInput.attrs({
  placeholderTextColor: "red"
})`
  background-color: "#000";
`;

你可以试试:

export const NewTodo = styled.input`
  padding: 16px 16px 16px 60px;
  font-weight: 300;
  font-size: 15px;
  ::placeholder,
  ::-webkit-input-placeholder {
    color: red;
  }
  :-ms-input-placeholder {
     color: red;
  }
`;

如何使用带样式的组件设置输入占位符的样式?

添加到@Fernando Pascoal Gomes 的回答中,如果您希望访问 theme 对象,请考虑将函数传递给 .attrs(),returns 组件继承的对象它的道具。

对于您的情况,TextInput 接受 placeholderTextColor 道具,因此它可能看起来像这样:

const Input = styled.TextInput.attrs((props) => ({
  placeholderTextColor: props.theme.palette.placeholderColor,
}))`
  background-color: #fff;
  color: #000;
  ...
`