有没有一种方法可以只使用键盘而不输入任何文本并在onChange上获取其值?
我只想在按钮单击事件上显示键盘,并在没有任何输入的情况下在视图中呈现其键入值。
什么是实现此目的的正确方法?
最佳答案
您可以添加一个虚拟TextInput并将onPress按钮设置为TextInput上的焦点以显示键盘。使用“ 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>
);
}
}
应用预览