在本机react中单击提交按钮后清除文本输入数据

IT技术 reactjs react-native
2021-05-06 01:56:11

嗨,我想在 react-native 代码的文本输入中提交 val 后清除文本这是我的代码

export default function AddTodo({onSubmit}) {
    const [text, setText] = useState('')
    const changeHandler = (val) => {
        setText(val)
    }
    return (
        <View>
            <TextInput
                style={styles.newInput}
                placeholder="Add task"
                onChangeText={changeHandler}
            />
            <Button onPress={() => onSubmit(text)} title="Add Task" color='#1881e9' />
        </View>
    )
}
4个回答

像这样向您的 TextInput 添加一个 value 属性

<TextInput
                style={styles.newInput}
                placeholder="Add task"
                onChangeText={changeHandler}
                value = {text}
            />

然后在像这样提交时清除文本

  <Button onPress={() => {
            onSubmit(text)
            setText('') }} title="Add Task" color='#1881e9' />

总代码将是这样的:

import React from 'react';
import {View,Text, TextInput, Button} from 'react-native';
import  {useState} from 'react';
export default function AddTodo({onSubmit}) {
    const [text, setText] = useState('')
    const changeHandler = (val) => {
        console.log("val is",val);
        setText(val)
    }

    return (
        <View style={{marginTop:100}}>
            <TextInput
                placeholder="Add task"
                onChangeText={changeHandler}
                value={text}
            />
            <Button onPress={() => {
                onSubmit(text)
                setText('') }} title="Add Task" color='#1881e9' />
        </View>
    )
}

希望这可以帮助!

这是解决您的问题的代码片段。

export default function AddTodo({onSubmit}) {
const [text, setText] = useState('')
const changeHandler = (val) => {
    setText(val)
}

const handleSumit = () => {
    // perform the summit operation
    setText("");
}
return (
    <View>
        <TextInput
            style={styles.newInput}
            placeholder="Add task"
            onChangeText={changeHandler}
        />
        <Button onPress={handleSumit} title="Add Task" color='#1881e9' />
    </View>
)

}

不调用参数 onSubmit()

<Button onPress={() => onSubmitAndClear(text)} title="Add Task" color='#1881e9' />

    const onSubmitAndClear() = (text) => {
            setText(text)
         /// after submit operation then clear

          setText('')
        }

您可以使用您的 ref TextInput,并直接分配您的文本,例如

refOfTextInput.setNativeProps({ text: "hello world" })

为了得到TextInput的参考,你可以使用这种方法

<TextInput ref={(ref) => { this.refOfTextInput = ref; }} />

所以在你的文本回调或任何其他组件中,如果你有你的参考,TextInput你可以像这样使用它

        const onSubmitAndClear() = (text) => {
            refOfTextInput.setNativeProps({ text: "hello world" })
        }