react-native - 我如何使 TextInput 在 react native 提交后清除
问题描述
我的代码中有一个 TextInput 在提交后不会自行清除,我不知道它为什么这样做或如何解决它。我看过其他有这种问题的帖子?但没有一个有效,或者我真的不知道在哪里放置代码以在提交后使其清楚。
代码
import React, { useState } from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
Button,
} from 'react-native';
export default function AddList({ submitHandler }) {
const [text, setText] = useState('');
const changeHandler = (val) => {
setText(val);
}
return(
<View style={styles.container}>
<View style={styles.wrapper}>
<TextInput
style={styles.input}
placeholder='text'
onChangeText={changeHandler}
/>
<Button onPress={() => submitHandler(text)} title='ADD' color='#333' />
</View>
</View>
);
}
解决方案
只需在 useState 之后创建一个新函数,如下所示:
const onSubmit = useCallback(() => {
if (submitHandler) submitHandler(text)
setText("")
}, [text])
并修改文本输入和按钮如下:
<TextInput
style={styles.input}
placeholder='What Tododay?'
onChangeText={changeHandler}
value={text}
/>
<Button
onPress={onSubmit}
title='ADD TO LIST'
color='#333'
/>
不要忘记从 react 中导入 useCallback。
我希望它对你有帮助。
推荐阅读
- c# - 我可以将 mdb vue (Material Design Vue) 与 Bootstrap Vue 一起使用吗?有哪些风险?
- django - Django 使用 .set 添加多个 m2m 相关模型记录工作正常,但如何添加除 ids 之外的其他模型字段?
- python - 如何通过 django 和请求获得 http 长连接?
- python - 如何通过python使用psutil获取cpu_persent
- android - 谷歌助手与 Android 应用程序的对话
- javascript - 如何使用 redux saga 从 redux 商店获取商品:已解决
- sql - 检查约束-1
- python-requests - 如何将表单数据中的国家/地区代码发布到 URL 以获取预期的 WebData?
- php - 将图像上传到 GoDaddy PHP 表单
- reactjs - 错误:使用 react-hooks 时超出最大更新深度