[英]how to listen button click event in react?
我正在使用下面的 package 在反應中動態生成表單:
https://www.npmjs.com/package/react-formio
我發現一個例子, on button click, an event is listening
https://jsfiddle.net/Formio/obhgrrd8/?utm_source=website&utm_medium=embed&utm_campaign=obhgrrd8
我想用上面的react
做同樣的事情這是我的代碼
https://codesandbox.io/s/lucid-austin-vjdrj
我有三個按鈕我想聽button click event
ReactDOM.render(
<Form src="https://wzddkgsfhfvtlmv.form.io/parentform" />,
// <Form src="https://peb3z.sse.codesandbox.io/abc" onSubmit={(i)=>{console.log(i)}} />,
rootElement
);
在這種情況下,您需要 select 一個事件作為按鈕模式的操作。
並給出一個事件名稱(比如eventFromButton1 )。
並在<Form />
組件中,添加onCustomEvent
。
<Form
form={{
onCustomEvent={customEvent => {
console.log(customEvent);
}}
/>
onCustomEvent
function 將收到具有以下結構的道具 object
{
type: "eventFromButton1",
component: {},
data: {},
event: MouseEvent
}
您可以使用type
屬性來識別哪個按鈕觸發了更新,並使用data
屬性來獲取表單數據。
嘗試使用下面添加的按鈕修改表單數據(我在react-formio
中沒有看到關於這些自定義的良好文檔)
使用submission
數據作為反應state
。
更改 onCustomEvent 上的onCustomEvent
並重新呈現表單。
import React, { useState } from "react";
import { Form } from "react-formio";
function CustomForm() {
const [submission, setSubmission] = useState({});
return (
<div className="App">
<Form
form={{
components: [
{
label: "First Name",
validate: { required: true, minLength: 3 },
key: "firstName",
type: "textfield",
input: true
},
{
type: "textfield",
key: "lastName",
label: "Last Name",
placeholder: "Enter your last name",
input: true
},
{
label: "Pupulate Nast Name",
action: "event",
showValidations: false,
key: "submit1",
type: "button",
input: true,
event: "someEvent"
},
{
type: "button",
label: "Submit",
key: "submit",
disableOnInvalid: true,
input: true
}
]
}}
submission={{ data: submission }}
onSubmit={a => {
console.log(a);
}}
onSubmitDone={a => {
console.log(a);
}}
onCustomEvent={customEvent => {
console.log(customEvent);
setSubmission({ ...customEvent.data, lastName: "Laaast Name" });
}}
/>
</div>
);
}
export default CustomForm;
不過形式上還是有一些小問題。
您會在 UI 中看到閃爍。
驗證錯誤將消失(看起來提交按鈕仍然被禁用)
試試這個沙盒
您也可以嘗試使用文檔中提到的 redux。
最后反應生成 javascript 代碼。 因此,您也可以在反應中使用類似於 javascript 的事件。
例如,
const submit = ()=>{
//your work goes here
}
return (
<div onClick={submit}> // or onClick={ ()=>submit()}
</div>
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.