【问题标题】:React Native - Show keyboard and render its values without using an inputReact Native - 在不使用输入的情况下显示键盘并呈现其值
【发布时间】:2019-08-19 02:52:51
【问题描述】:

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

我想仅在按钮单击事件上显示键盘,并在视图中呈现其键入值而无需任何输入。

什么是正确的实现方式?

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    您可以在 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>
        );
      }
    }
    
    

    应用预览

    【讨论】:

    • 是的,这就是解决方法(有点像 hack)。但我认为这也是我能想到的处理这种情况的唯一方法。顺便说一句,答案很好!
    猜你喜欢
    • 1970-01-01
    • 2018-01-23
    • 2021-09-21
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 2020-02-24
    • 1970-01-01
    • 2020-03-23
    相关资源
    最近更新 更多