【问题标题】:Change the color of a TextInput placeholder with Styled Components in React Native在 React Native 中使用样式化组件更改 TextInput 占位符的颜色
【发布时间】:2019-10-13 06:21:59
【问题描述】:

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


    【解决方案1】:

    最好的方法:

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

    【讨论】:

    • 这对我有用,但我无法访问 theme 对象来获取颜色。硬编码值似乎可以正常工作。
    • @HaseebBurki 试试color: ${themeColor};
    【解决方案2】:

    你可以试试:

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

    How do I style an input placeholder with Styled Components?

    【讨论】:

      【解决方案3】:

      除了@Fernando Pascoal Gomes 的回答之外,如果您希望访问theme 对象,请考虑将一个函数传递给.attrs(),该函数返回一个组件为其道具继承的对象。

      对于您的情况,TextInput 接受 placeholderTextColor 属性,因此它可能如下所示:

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

      【讨论】:

        【解决方案4】:

        您不能直接使用 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

        【讨论】:

        • 好的,谢谢。当然,这不是我所希望的。我怎么知道哪些属性是可能的,哪些不是?这是在某个地方记录的吗?
        • @Wannes 这并没有真正记录在案,但不支持与特定浏览器相关的所有内容。比如::placeholder等等
        【解决方案5】:

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

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

        【讨论】:

          猜你喜欢
          • 2016-06-05
          • 2020-03-12
          • 2018-04-10
          • 1970-01-01
          • 1970-01-01
          • 2020-03-27
          • 2019-12-31
          • 1970-01-01
          • 2016-06-12
          相关资源
          最近更新 更多