javascript - 如何使用 React Native 中的引用更改 TextInput 的值?
问题描述
我正在使用 React Native0.57.8
和 React 16.7.0
。我正在为 Android TV 创建一个屏幕键盘,将用作库。我有一个TextInput
我分配给他的参考。如何使用此参考来value
更改TextInput
?
constructor(props) {
super(props);
this.emailRef = React.createRef();
}
<TextInput
ref={this.emailRef}
placeHolder="Email Address"
blurOnSubmit={false}
/>
<Keyboard textInput={this.emailRef} />
图书馆内:
<Button
text="change value"
onPress={() => {
this.props.emailRef.current.props.value =
this.props.emailRef.current.props.value + "q";
}}
/>
解决方案
他们都说使用状态,但不知道为什么我确实需要在不使用状态的情况下更新 UI。在我的例子中,文本输入正在使用状态,当输入非常快时,异步状态和 UI 更新滞后于输入速度,并且光标滞后几个字母,导致输入错误。防止这种情况的唯一方法是不使用任何状态!如果你不使用状态,你不能给文本输入一个初始值而不使它成为只读的。为了给 TextInput 一个初始值,我们可以使用 ref 并在组件挂载事件时以编程方式设置原生 props。像这样:
const setInitialBio = React.useCallback(() => {
if(inputRef.current) {
inputRef.current.setNativeProps({ text: "initial value goes here" })
}
}, []);
推荐阅读
- python - 烧瓶 + IIS + 运动 JPEG
- python - python中美汤爬取的具体a href
- javascript - 有没有办法从对象数组中获取 html 内容?
- java - 如何在单个editText中添加多个sytleSpan?
- ssis - 使用脚本任务使用表名和日期的变量从表中删除记录
- python - 当链接查询参数有项目数而不是页码时如何抓取多个页面?
- selenium - 错误 selenium.common.exceptions.ElementNotInteractableException:消息:元素不可交互
- javascript - 我无法通过 post 路由输入对象,而只能在节点 js 中未定义
- mongodb - TypeError:无法使用nodejs在monogdb中读取null的属性“项目”
- css - 如何使 Div(紫色框)容器中的内容响应