问题
I am using the package below to generate a form dynamically in react:
https://www.npmjs.com/package/react-formio
I found one example where on button click, an event is listening
https://jsfiddle.net/Formio/obhgrrd8/?utm_source=website&utm_medium=embed&utm_campaign=obhgrrd8
I want to do same thing in react
using the above package
here is my code
https://codesandbox.io/s/lucid-austin-vjdrj
I have three buttons I want to listen 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
);
回答1:
In this case you need to select an event as action from the button modal.
And give an event name(say eventFromButton1).
And in the <Form />
component, add onCustomEvent
prop.
<Form
form={{
onCustomEvent={customEvent => {
console.log(customEvent);
}}
/>
onCustomEvent
function will receive a prop object with following structure
{
type: "eventFromButton1",
component: {},
data: {},
event: MouseEvent
}
You can use the type
property to identify which button triggered the update, and use the data
property to get the form data.
An attempt to modify the form data using a button added below (I don't see good documentation on these customizations in react-formio
)
Uses submission
data as react state
.
Alter the state on onCustomEvent
and re-render the form.
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;
There are some glitches in form though.
You would see a flicker in UI.
Validation errors would be gone(Looks like submit button is still disabled though)
Try this Sandbox
Also you can try using redux as mentioned in documentation.
回答2:
react at the end generates javascript code. So, you can use the events similar to javascript in react as well.
For example,
const submit = ()=>{
//your work goes here
}
return (
<div onClick={submit}> // or onClick={ ()=>submit()}
</div>
)
来源:https://stackoverflow.com/questions/58686378/how-to-listen-button-click-event-in-react