我想從一個按鈕提交兩個表單next.js而不使用document.getElementById.
我正在使用兩個表單標簽并在兩個不同的物件中獲取它們的資料,并且我希望通過一個按鈕立即提交它們。
我試過這樣做,document.getElementById.Submit() 但它引發了一個錯誤,即檔案未定義。
已經在 SO 上提出了類似的問題,但提供的解決方案是使用JQuery我無法使用的。
const submitForms = function () {
useEffect(()=>
{
document.getElementById("form1").submit();
document.getElementById("form2").submit();
})
};
請告訴我我哪里出錯了?
uj5u.com熱心網友回復:
您可以使用函式,并在提交表單時,在函式的第一行使用:
e.preventDefault()
當點擊另一個按鈕時,呼叫這個函式,當表單提交時也運行這個函式
使用 ReactJs 或 NextJs 時不要使用 DOM 函式
uj5u.com熱心網友回復:
基本原理是將表單資料存盤在狀態中,在表單資訊更改時更新狀態,然后在單擊按鈕時將狀態資料提交給處理該資料的服務器端點。
在這個作業示例中,我們使用一個物件作為狀態,并為每個表單分配一個 id(參見資料屬性)。我們將偵聽器附加到表單上,這樣當任何輸入發生變化時,我們可以捕獲它們在 DOM 中冒泡的事件(事件委托)。
在handleChange函式中,我們從形式 ( currentTarget) 的資料集中獲取 id ,以及來自已更改元素的名稱和值 ( target) - 更多關于此處的關鍵差異- 然后使用該資訊更新狀態。
handleClick 然后將狀態字串化,此時您可以將其提交到服務器端點。
重新審視React 的作業原理可能會讓您受益。它有自己的 DOM 更新方式,這意味著您不應使用任何原生 DOM 方法。
const { useEffect, useState } = React;
function Example() {
// Set the state
const [ forms, setForms ] = useState({});
function handleChange(e) {
// Destructure the id from the dataset of the form
const { dataset: { id } } = e.currentTarget;
// Destructure the name and value from the
// element that changed
const { name, value } = e.target;
// Update the state. We preserve the existing
// state data using the spread syntax, and set the new
// value of the property that has the id as key.
// That new value is an object representing the old
// value data (again using the spread syntax), and
// updating the property using the element name and value.
setForms({
...forms,
[id]: { ...forms[id], [name]: value }
});
}
function handleClick() {
// Stringify the data. You can now use
// `fetch` or something like Axios to send the
// data to the server
console.log(JSON.stringify(forms));
}
return (
<div>
<form data-id="formone" onChange={handleChange}>
<fieldset>
<legend>Form 1</legend>
Name: <input name="name" />
<br/>
Age: <input name="age" />
</fieldset>
</form>
<form data-id="formtwo" onChange={handleChange}>
<fieldset>
<legend>Form 2</legend>
Role: <input name="role" />
</fieldset>
</form>
<button
type="button"
onClick={handleClick}
>Submit all form data
</button>
</div>
);
};
ReactDOM.render(
<Example />,
document.getElementById('react')
);
form, button { margin-top: 1em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
附加檔案
傳播語法
解構賦值
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/361093.html
標籤:javascript 反应 下一个.js
下一篇:開發一個JavaScript來查找給定字串“efg”第3次出現的位置I/P:abcefgacefgabcceftyefghjklopO/p:20
