0

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

    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组件,并且可以调用onFocusTextInput的方法

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

4

1 回答 1

0

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

  1. 确保 的背景TextInput是透明的或至少与Text. 当我们给予时,这种方式Text仍然可见position: absolute。然后我们
  2. 我们需要zIndexText低于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

于 2019-07-29T06:36:48.943 回答