使用 React hooks 清除输入字段

Clear input field using React hooks

我正在构建一个实时聊天应用程序,但在清除输入字段时遇到了问题。提交表单后,我希望清除输入字段。我将状态更改为空的 sdtate 但根本没有工作。

import React, { useState, useEffect, useContext } from 'react'
import io from 'socket.io-client'
import './ChatRoom.css'
import { ChatContext } from '../ChatContext'
import ScrollToBottom from 'react-scroll-to-bottom'


const ChatRoom = () => {
    const { userName, setUserName } = useContext(ChatContext)
    const { roomCode, setRoomCode } = useContext(ChatContext)
    const [message, setMessage] = useState('')
    const [chats, setChats] = useState([])

    const handleMessage = (e) => {
        var newMessage = e.currentTarget.value
        // console.log(newMessage)
        setMessage(newMessage)
    }

    const handleSubmit = (e) => {
        e.preventDefault()
        console.log('Message submitted')
        setMessage("")
    }

    return (
        <>
            <div className="top-container">
                <h2>123</h2>
            </div>
            <div className="chat-container">
            {/* {renderChat()} */}
            <h1>hello</h1>
            </div>
            <form className="form-inline" onSubmit={handleSubmit}>
                <input type="text" onChange={handleMessage} className="form-control mb-2 mr-sm-2" id="inlineFormInputName2" placeholder="Type your message here..."/>
                <button type="submit" className="btn btn-primary mb-2">Send</button>
            </form>
        </>
        
    )
}


export default ChatRoom;

您正在使用 uncontrolled input。尝试在输入上设置 value={message}

添加值属性并绑定消息状态字段,如下所示。

<input type="text" onChange={handleMessage} value={message} className="form-control mb-2 mr-sm-2" id="inlineFormInputName2" placeholder="Type your message here..."/>

您忘记使用 React 控制输入字段。添加一个 value 道具:

<input type="text" onChange={handleMessage} className="form-control mb-2 mr-sm-2" id="inlineFormInputName2" placeholder="Type your message here..." value={message}/>