1

I am using react-bootstrap/Modal and react-hook-form. I want the user to insert data in the input which after submitting will go to the function where I want to make an object with it.

<form onSubmit={handleSubmit(update)}>
                        <Modal show={show} onHide={handleClose}>
                            <Modal.Header closeButton>
                                <Modal.Title>Edit</Modal.Title>
                            </Modal.Header>
                            <Modal.Body>
                                <label>Description</label>
                                <input name="message" type="text" ref={register} placeholder="description"/>
                            </Modal.Body>
                            <Modal.Footer>
                                <button variant="secondary" onClick={handleClose}>
                                    Cancel
                                </button>
                                <button type="submit" variant="primary" onClick={update}>
                                    Edit
                                </button>
                            </Modal.Footer>
                        </Modal>
                    </form>



//I will need the async function later to await an api call.
const update = (data) => {
        (async () => {
            console.log("data", data)
        })()
    }


Thanks for helping!

EDIT:

I found the solution, I had to put the form in the modal but outside the modal components.

<Modal show={show} onHide={handleClose}>
    <form onSubmit={handleSubmit(update)}>
        <Modal.Header closeButton>
            <Modal.Title>Edit</Modal.Title>
        </Modal.Header>
        <Modal.Body>
            <label>Description</label>
            <input name="message" type="text" placeholder="description" />
        </Modal.Body>
        <Modal.Footer>
            <button variant="secondary" onClick={handleClose}>
                Cancel
            </button>
            <button type="submit" variant="primary" onClick={update}>
                Edit
            </button>
        </Modal.Footer>
    </form>
</Modal>
4

1 回答 1

1

由于您使用的是react-hook-forms,所以表单提交后就可以得到结果。

在您的情况下,结果对象如下所示: {message: "some message data"}

因此,您需要获取函数data参数的“消息”属性update

注意:message您作为元素的 name 属性传递,input因此data.message将为您提供有关元素的相应数据,input该数据由react-hook-forms

const update = (data) => {
        (async () => {
            console.log("data", data.message)
        })()
    }
于 2021-10-19T11:14:56.307 回答