【问题标题】:React Native Custom TextInput PlaceholderReact Native 自定义 TextInput 占位符
【发布时间】:2018-08-09 08:09:12
【问题描述】:

我知道您可以动态更改占位符文本和样式,但是您可以一起创建自定义占位符视图吗?

这就是我想要实现的目标:

有可能做这样的事情吗?

【问题讨论】:

  • 您可以创建自己的自定义TextInput组件
  • 你能发一个小例子吗?
  • @cnps 怀疑它,这回答了如何设置它的样式,但是在我添加的屏幕截图中,您可以看到有两种不同的颜色,并且没有涵盖。

标签: javascript reactjs react-native


【解决方案1】:

我建议你在功能组件中使用自定义样式。创建一个名为RenderInput 的功能组件,将placeholder 作为道具传递。

import React, {Component} from 'react';
import {TextInput, View, Text} from 'react-native';

const RenderInput = ({ label , inputvalue,styleLabel, ipOnChangeText, placeholder}) => {
    const {inputStyle, labelStyle, containerStyle} = styles;
    return(
        <View style = {containerStyle}>
            <Text style= {styleLabel ? labelStyle : ""} >{label}</Text>
            <TextInput 
               autoCorrect={false}
               placeholder={placeholder}
               style= {inputStyle}
            />
        </View>
    );
 }

const styles ={
    inputStyle:{
        color: '#333',
        fontSize: 16,
        lineHeight: 23,  
        borderBottomColor: '#333',
        borderBottomWidth: 0.5,
        fontFamily: 'System',
    },
    labelStyle:{
        fontSize: 18,
        color: '#737373',
        paddingBottom: 10,
        fontFamily: 'System',
        position: 'relative',
        ':after': {
           content: '* ',
           position: absolute,
           left: 5,
           top: 0,
           color: '#bbb'
        }
    },
    containerStyle:{
        flexDirection: 'column',
        marginTop: 10,
        marginBottom: 10
    }
}
export { RenderInput };

【讨论】:

  • 嘿,非常感谢您的回答,但是我使用的是 React Native 而不是 Web 应用程序。有没有办法在 React Native 应用程序中使用它?
  • 我看到答案是为 React Native 编辑的。我只能明天测试,但看起来不错!
【解决方案2】:

创建一个名为 MyTextInput 的组件,如下所示:

class MyTextInput extends Component {
  constructor(props) {
    super(props);
    this.state = { placeholder: props.text.length == 0 }
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(ev) {
    this.setState({ placeholder: ev.nativeEvent.text.length == 0 }); 
    this.props.onChange && this.props.onChange(ev); 
  }
  render() {
    const { placeholderStyle, style, onChange, ...rest } = this.props;

    return <TextInput 
      {...rest} 
      onChange={this.handleChange}
      style={this.state.placeholder ? [style, placeholderStyle] : style}
      />
  }
}

并在另一个组件中使用它:

import MyTextInput from '.../MyTextInput';

<MyTextInput 
  text={this.state.myText}
  style={{ fontFamily: "Your Font" }}
  placeholderStyle={{ fontFamily: "AnotherFont", borderColor: 'red' }}
/>

您可以通过这种方式自定义任何您想要的组件。

【讨论】:

  • 您实际上是从重复问题中复制/粘贴了答案。至少你可以称赞作者。
【解决方案3】:

你可以这样做

<TextInput 
  placeholder="YOUR TEXT"
  placeholderTextColor="#555555"
/>

当然,您也可以创建自己的组件 TextInput 版本,其中包含 TextInput 顶部的自定义占位符,一旦文本更改,您就隐藏自定义占位符

【讨论】:

    猜你喜欢
    • 2017-04-01
    • 1970-01-01
    • 2023-03-21
    • 2020-03-12
    • 2021-05-13
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    相关资源
    最近更新 更多