簡體   English   中英

我如何在 react native 中構建一個文本輸入,它有一個占位符,單擊時會在頂部更改為 textview

[英]how do I build a text input in react native that has a placeholder that changes to a textview on top when clicked

我對本地反應有點陌生,我有一個需要幫助的問題

如何在 react native 中構建文本輸入,該文本輸入有一個占位符,單擊時會更改為頂部的文本視圖? 類似於下面的截圖

空文本輸入字段在默認狀態下看起來像這樣

空文本字段/默認狀態

輸入數據的文本字段

用文本填充的文本輸入字段看起來像這樣

看到空的輸入文本有一個占位符出現在輸入文本字段的中間

參見第二張圖,一旦用戶開始在輸入字段中輸入文本,占位符文本就會移動到輸入字段的頂部

這是我在沒有庫的情況下使用的工作示例,如果您想將動畫添加到帶有動畫的字段工作示例中

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

class FloatingLabelInput extends Component {
  state = {
    isFocused: false,
  };

  handleFocus = () => this.setState({ isFocused: true });
  handleBlur = () => this.setState({ isFocused: false });

  render() {
    const { label, ...props } = this.props;
    const { isFocused } = this.state;
    const labelStyle = {
      position: 'absolute',
      left: 0,
      top: !isFocused ? 18 : 0,
      fontSize: !isFocused ? 20 : 14,
      color: !isFocused ? '#aaa' : '#000',
    };
    return (
      <View style={{ paddingTop: 18 }}>
        <Text style={labelStyle}>
          {label}
        </Text>
        <TextInput
          {...props}
          style={{ height: 26, fontSize: 20, color: '#000', borderBottomWidth: 1, borderBottomColor: '#555' }}
          onFocus={this.handleFocus}
          onBlur={this.handleBlur}
          blurOnSubmit
        />
      </View>
    );
  }
}


export default class App extends Component {
  state = {
    value: '',
  };

  handleTextChange = (newText) => this.setState({ value: newText });

  render() {
    return (
      <View style={{ flex: 1, padding: 30, backgroundColor: '#f5fcff' }}>
        <StatusBar hidden />
        <FloatingLabelInput
          label="Email"
          value={this.state.value}
          onChangeText={this.handleTextChange}
        />
      </View>
    );
  }
}

最簡單的方法是使用帶有文本輸入的react-native-paper包:

import * as React from 'react';
import { TextInput } from 'react-native-paper';

const MyComponent = () => {
  const [text, setText] = React.useState('');

  return (
    <TextInput
      label="Email"
      value={text}
      onChangeText={text => setText(text)}
    />
  );
};

export default MyComponent;

結果:

輸入

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM