简体   繁体   中英

How to pass <form> data to an object array in React

I'm trying to make this simple component where I type a message in the input box and the component returns the message in a list underneath the input field. However when I click the submit button the only thing that appears below is a blank bullet point

import React, { useState } from 'react'

function Form(props) {
    const [message, setMessage] = useState([])

    const addMessageHandler = (event) => {
        event.preventDefault()

        const data = new FormData(event.target);

        const _data = data.get('input')

        setMessage([...message, { id: message.length, value: _data }])
    }

    return (
        <div>
            <form onSubmit={addMessageHandler} id='input'>
                <label>Type a Message</label>
                <input type='text'></input>
                <button type='submit'>Submit</button>
            </form>

            <ul>
                {
                    message.map(msg => (
                        <li key={msg.id}>{msg.value}</li>
                    ))
                }
            </ul>
        </div>
    )
}

export default Form

All ways add "id" & "name" attributes to input fields.

  <label htmlFor="chat_box">Type a Message</label>
  <input type='text' id="chat_box" name="chatbox_input" />

now you can access input elements in e.currentTarget.elements , just make sure you have give unique names to input tags.

const addMessageHandler = (event) => {
  event.preventDefault()
  setMessage((message) => [...message, { id: message.length, value:  e.currentTarget.elements['chatbox_input'].value }])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM