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

问题描述 投票:0回答:6

如何使用 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;
   }
`
react-native styled-components
6个回答
16
投票

制作这个的最佳方法:

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

9
投票

你可以尝试:

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;
  }
`;

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


5
投票

补充 @Fernando Pascoal Gomes 的答案,如果您希望访问

theme
对象,请考虑将一个函数传递给
.attrs()
,该函数返回组件为其 props 继承的对象。

对于您的情况,

TextInput
接受
placeholderTextColor
道具,所以它可能看起来像这样:

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

3
投票

您无法直接使用样式组件设置占位符颜色的样式,但您可以将

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


0
投票

更改文本输入占位符的文本颜色用户属性 “占位符文本颜色” 例如

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

0
投票

不知道为什么这个答案如此过时,但这些都不适合我,就这么简单:

export const SearchInput = styled.input<MTStyledProps>`
    
    &::placeholder {
        color: ${onlyTheme.color.lightGrey};
    }

`;
© www.soinside.com 2019 - 2024. All rights reserved.