【问题标题】:How do i make so the TextInput clears after submit in react native我如何使 TextInput 在 react native 提交后清除
【发布时间】:2020-01-25 18:24:25
【问题描述】:

我的代码中有一个 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>
 );
}

【问题讨论】:

    标签: react-native react-native-textinput


    【解决方案1】:

    在 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。

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2017-12-28
      • 2015-06-07
      • 2022-12-17
      • 1970-01-01
      • 2021-03-29
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多