React Native 中的下划线占位符

Underline placeholder in React Native

如何在 React Native 中为 iOS 中的占位符添加下划线?我可以通过以下方式在整个 TextInput(不是占位符)下划线:

borderBottomWidth: 1,
borderBottomColor: '#B8B8B8',

我只想强调 TextInput 的占位符,而不是 TextInput

我为您提供了一些解决方法。一旦您开始输入,下划线就会被删除。

演示

说明

我将 borderBottomWidthborderBottomColor 应用于父视图,因为您可能不想使用 multiline。如果您想使用多文本输入,您可以将这些样式直接应用于文本输入,如 docs 中所述。

Note that some props are only available with multiline={true/false}. Additionally, border styles that apply to only one side of the element (e.g., borderBottomColor, borderLeftWidth, etc.) will not be applied if multiline=false. To achieve the same effect, you can wrap your TextInput in a View

一旦用户输入(文本长度大于 0)内容,this.setState({ active: true }) 就会被触发。之后条件渲染发生在这里:

borderBottomColor: this.state.active === false ? 'red' : 'transparent' // hide color, when text is present
width: this.state.active === false ? scaledWidth : 100 // increase width to 100. Value is just a placeholder, use whatever you like

完整代码

// helper function to scale font size and placeholder width.
scale = (fontSize) => {
    const screenWidth = Dimensions.get('window').width; 
    const ratio = fontSize / 375; // get ratio based on your standard scale, here: width of iphone 7
    const newSize = Math.round(ratio * screenWidth);
    return newSize; 
  }


render() {
   // you probably have to play around with those standard values 
   const scaledFontSize = this.scale(22); 
   const scaledWidth = this.scale(25);    
   return (
      <View style={{ marginTop: 50, flex: 1, alignItems: 'flex-end' }}>
         <View style={{ borderBottomWidth: 2, borderBottomColor: this.state.active === false ? 'red' : 'transparent', width: this.state.active === false ? scaledWidth : 100  }}>
             <TextInput
             style={{ height: 30,  textAlign: 'right', fontSize: scaledFontSize }}
             onChangeText={(text) => text.length > 0 ? this.setState({ active: true }) : this.setState({ active: false })}
             placeholder={'10'}
             //multiline 
             />
        </View>
     </View>
   )
}