首页 > 解决方案 > React Native - 在不使用输入的情况下显示键盘并呈现其值

问题描述

有没有办法只使用键盘而不输入任何文本并获取其值 onChange?

我想仅在按钮单击事件上显示键盘,并在没有任何输入的情况下在视图中呈现其键入值。

实现这一点的正确方法是什么?

标签: javascriptreact-native

解决方案


您可以在 TextInput 上添加一个虚拟 TextInput 和 onPress 按钮设置焦点以显示键盘。使用“onChangeText”属性保存状态并在视图中显示

完整代码

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

export default class App extends React.Component {
  state = { text: "" };

  render() {
    return (
      <View style={{ flex: 1, marginTop: 50 }}>
        <TextInput
          style={{ height: 0, width: 0, borderWidth: 0 }}
          onChangeText={text => this.setState({ text })}
          ref={ref => {
            this.textInput = ref;
          }}
          autoCapitalize="none"
          autoCorrect={false}
          autoFocus={false}
        />
        <Button
          onPress={() => {
            this.textInput.focus();
          }}
          title="Press Me To show Keyboard"
          color="#841584"
        />
        <View
          style={{
            borderColor: "red",
            borderWidth: 1,
            padding: 16,
            marginTop: 20
          }}
        >
          <Text style={{ marginBottom: 8 }}>Show Typing Values:</Text>
          <Text>{this.state.text}</Text>
        </View>
      </View>
    );
  }
}

应用预览

在此处输入图像描述


推荐阅读