我的代码中有一个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。
希望对您有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句