[英]useState hook not working inside onKeyPress handler in React Native's TextInput
I'm using useState
to keep the value of an input, and I need make some stuff when the taps a specific key, so I'm try to use onKeyPress
, but the method used to update the state is not working, any help aprecciated :)我正在使用
useState
来保持输入的值,当点击特定键时我需要做一些事情,所以我尝试使用onKeyPress
,但是用于更新状态的方法不起作用,任何帮助都值得赞赏:)
Here how the code looks like:代码如下所示:
...
function handleKeyPress(event) {
// This code looks like is not running, why?
setMessageInput('asdasdasdasd')
}
...
<TextInput onKeyPress={handleKeyPress} />
...
It looks like you need to bind the function to the onKeyPress event handler.看起来您需要将该函数绑定到 onKeyPress 事件处理程序。 You can easily accomplish this by using an arrow function .
您可以使用箭头函数轻松完成此操作。
function handleKeyPress(event) {
setMessageInput('asdasdasdasd')
}
...
<TextInput onKeyPress={(e) => handleKeyPress(e)} />
The problem with yours is a javscript statement , where functions in javascript needs explicit binding of this in class components and in functional components you can achieve the same by using fat arrow functions.您的问题是一个 javscript 语句,其中 javascript 中的函数需要在类组件和功能组件中显式绑定 this ,您可以通过使用粗箭头函数来实现相同的效果。
So try replacing the code with the below所以尝试用下面的代码替换
const handleKeyPress = (event) => {
setMessageInput('asdasdasdasd')
}
...
<TextInput onKeyPress={(e) => handleKeyPress(e)} />
Hope it helps.希望能帮助到你。 feel free for doubts
随意怀疑
我解决了这个问题,这是另一个处理程序异步执行的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.