繁体   English   中英

ReactJS:在更改时提交表单

[英]ReactJS: submit form onChange

我有一个文件输入标签,我想在 state 更改时触发表单提交(选择文件上传)。

我想触发表单提交的原因是因为提交会触发所需元素的验证。

export default function Add() {
    const [status, setStatus] = useState('Upload a menu')

    //Create a ref to access a DOM element
    const fileInput = useRef(null) //<input type='text' />
    const form = useRef(null) // <form></form>

    //Used by the onChange prop to handle changeEvents, like addEventListener('change', )
    function handleUploads() {


        //******What do I put in here?*****

    }

    function handleSubmit() {
        setStatus('Uploading...')
        const resto = document.getElementById('resto')
        //Reference to the node accessible at 'current' attribute of ref
        const files = fileInput.current.files

        //Create a shallow-copied Array from files
        const filesArray = Array.from(files)
        filesArray.map(img => {
            const storageRef = storage.ref()
            const fileRef = storageRef.child(`menus/${resto}/${img.name}`)
            fileRef.put(img).then((snapshot) => {
                setStatus('Added!')
            })
        })
    }

    return (
        <section id="add">
            <form name="form" id="form" onSubmit={handleSubmit} ref={form}>
                <input type="text" placeholder="Restaurant" id="resto" required />
                <input type="file" capture="environment" accept="image/*" id="file" multiple
                    ref={fileInput} onChange={handleUploads} required
                />
                <label htmlFor="file">{status}</label>
                <button type="submit">Submit</button>
            </form>
        </section >
    )
} 

据我了解,我不能直接从 handleUploads() 调用 handleSubmit(),因为这不会触发浏览器对所需值的“验证”。 因此,我必须让浏览器认为我正在单击提交按钮。

问题是,通过 id 获取表单元素不会触发任何东西 ``` document.getElementById("form").submit() ````

我发现这个解决方案导致我使用refs获取 DOM 元素,并使用dispatchEvent强制提交form.current.dispatchEvent(new Event("submit"))

但是现在我想要的必需验证不计算在内。 是什么赋予了?

requestSubmit() function 可用于触发输入字段验证和提交,但它不兼容所有浏览器,因此需要回退

    //Check if requestSubmit() is available to current browser
    if (form.current.requestSubmit) {
        form.current.requestSubmit()
    }
    //If not, perform constraint validation and call submit function directly
    else {
        if (form.current.reportValidity()) {
                handleSubmit()
        }
    }

更多信息在这里:

  1. https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLFormElement/requestSubmit
  2. https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit
  3. https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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