繁体   English   中英

在 React Native 中单击 TextInput 时切换视图

[英]toggle view when clicked on TextInput in react native

我有一个TextInput ,因为我有一个视图,它使文本进入TextInput的上边框之间,如下图所示。

在此处输入图像描述

下面是我的代码:

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

const AddAddressScreen = () => {
    return (
        <View style={styles.TextInputcontainer}>
            <View style={styles.TextInputlabelContainer}> // this should toggle when clicked in and out of TextInput
                <Text style={styles.labelText}>Search</Text>
            </View>
            <TextInput style={styles.textSearchInput} selectionColor={"black"} placeholder="Search" />
        </View>
    );
}
const styles = StyleSheet.create({
    TextInputcontainer: {
        height: 50, width: 200, marginTop: 50,
    },
    TextInputlabelContainer: {
        position: 'absolute',
        backgroundColor: '#fff',
        top: -10.5, left: 20, zIndex: 1,
    },
    labelText: {
        color: "black",
    },
    textSearchInput: {
        flex: 1,
        borderWidth: 1, borderColor: "#9E9E9E",
        color: "#9E9E9E"
    },
});
export default AddAddressScreen;

styles.TextInputlabelContainer有观点,我也在那个地方写了评论。 我希望该view仅在用户单击TextInput时出现。 我仍处于 React Native 的学习阶段,所以我无法思考如何做到这一点。

尝试在 TextInput 中使用 onFocus 和 onBlur 方法:

您还可以从react-native 中的 TextInput 的下方链接焦点样式获取参考

使用onFocusonBlur属性设置可见性 state 并使用它来显示或隐藏TextInput label。

工作示例: Expo 小吃

在此处输入图像描述

解决方案:

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

const AddAddressScreen = () => {
  const [showLabel, setShowLabel] = useState(false);
  return (
    <View style={styles.TextInputcontainer}>
      {showLabel && (
        <View style={styles.TextInputlabelContainer}>
          <Text style={styles.labelText}>Search</Text>
        </View>
      )}
      <TextInput
        ref={btnRef}
        style={styles.textSearchInput}
        selectionColor={'black'}
        placeholder="Search"
        onFocus={() => {
          setShowLabel(true);
        }}
        onBlur={() => {
          setShowLabel(false);
        }}
      />
    </View>
  );
};
const styles = StyleSheet.create({
  TextInputcontainer: {
    height: 50,
    width: 200,
    marginTop: 50,
  },
  TextInputlabelContainer: {
    position: 'absolute',
    backgroundColor: '#fff',
    top: -10.5,
    left: 20,
    zIndex: 1,
  },
  labelText: {
    color: 'black',
  },
  textSearchInput: {
    flex: 1,
    borderWidth: 1,
    borderColor: '#9E9E9E',
    color: '#9E9E9E',
  },
});
export default AddAddressScreen;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM