简体   繁体   English

useState 钩子在 React Native 的 TextInput 中的 onKeyPress 处理程序中不起作用

[英]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.

相关问题 在自定义组件中调用 useState Hook 时反应本机 TextInput ReRenders - React Native TextInput ReRenders when calling useState Hook inside a custom component React Native TextInput 失去了对 useState 调用钩子的关注 - React Native TextInput loses focus on call hook from useState React native onKeyPress不工作? - React native onKeyPress is not working? TextInput onChangeText 设置 useState 值在 React Native Testing with Enzyme 中不起作用 - TextInput onChangeText set useState value is not working in React Native Testing with Enzyme React Native-TouchableOpacity和TextInput在ScrollView中不起作用 - React Native - TouchableOpacity and TextInput is not working inside ScrollView React Native useState 在 watchPositionAsync 内部不起作用 - React Native useState not working inside of watchPositionAsync React Native 无法识别 useState 钩子 - React Native not recognizing useState hook 在 React Native TextInput onKeyPress 中获取 cursor position,文本和键 - Get cursor position, text and key in a React Native TextInput onKeyPress 在 React Native 中使用 useState 钩子的 useAsyncStorage 自定义钩子 - useAsyncStorage custom hook with useState hook in React Native React本机TextInput边框不起作用 - React native TextInput border not working
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM