【问题标题】:Give styling to placeholder in TextInput in React Native在 React Native 中为 TextInput 中的占位符提供样式
【发布时间】:2019-07-29 06:17:37
【问题描述】:

所以我有一个 TextInput 并且占位符有一个样式。 为此,我将Textposition: 'absolute'zIndex: 1 放在TextInput 之前

    activeField(){
        this.setState({active: true})
    }

render(){

  return(

      { !this.state.active &&
       <Text style={STYLES.textInputPlaceholder}>
          {this.props.placeholder}
       </Text>
      }

      <TextInput
        style={STYLES.textInputField}
        onFocus={() => this.activeField()}
      />

  )
}

现在,带有占位符的Text组件,当我按下它时,我应该可以按下占位符,也就是这里的Text组件,并且可以调用TextInput的onFocus方法

我希望我能够清楚地解释我的问题。

【问题讨论】:

  • 嗨,Shubham,在下面试试我的解决方案。那应该对你有帮助:)

标签: reactjs react-native react-native-textinput react-native-text


【解决方案1】:

我们将无法通过单击Text 来触发TextInputonFocus 事件侦听器。但是,我们可以通过一些巧妙的 CSS 让它看起来像正在发生的事情。

  1. 确保TextInput 的背景是透明的或 至少与Text 匹配。这样,当我们提供position: absolute 时,Text 仍然可见。 那么我们
  2. 我们需要TextzIndex 低于zIndexTextInput。这样TextInput 实际上就在Text 前面。因此,虽然看起来您正在单击 placeholder,但实际上您只是在单击 TextInput,这将触发 onFocus 事件。

试试这个:

import React, { Component } from "react";
import { StyleSheet, Text, TextInput } from "react-native";

class App extends Component {
  state = {
    active: false,
    text: ""
  };

  activeField = () => {
    console.log("focused");
    this.setState({
      active: true
    });
  };

  handleOnBlur = () => {
    if (this.state.text.length === 0) {
      this.setState({
        active: false
      });
    }
  };

  render() {
    return (
      <div>
        {!this.state.active && (
          <Text style={STYLES.textInputPlaceholder}>
            {this.props.placeholder}
          </Text>
        )}
        <TextInput
          style={STYLES.textInputField}
          onChangeText={text => this.setState({ text })}
          onFocus={this.activeField}
          value={this.state.text}
          onBlur={this.handleOnBlur}
        />
      </div>
    );
  }
}

const STYLES = StyleSheet.create({
  app: {
    marginHorizontal: "auto"
  },
  textInputField: {
    zIndex: 1,
    width: 300,
    borderColor: "black",
    borderWidth: 1
  },
  textInputPlaceholder: {
    zIndex: -1,
    color: "blue",
    position: "absolute",
    backgroundColor: "transparent"
  }
});

export default App;

App.defaultProps = {
  placeholder: "Hello"
};

这是工作沙箱:https://codesandbox.io/s/react-native-on23p

【讨论】:

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