admin管理员组

文章数量:1128542

I am trying to develop a custom gutenberg block. I have a form in save.js:

export default function save() {
return (
    <div {...useBlockProps.save()}>
            <form onSubmit={handleSubmit}></form>
</div>);}

File view.js is defined in block.json ("viewScript": "file:./view.js",)

const handleSubmit = async (event) => {
event.preventDefault();

const formData = new FormData(event.target);
...
};

But when the block renders, it fails.

Uncaught ReferenceError: handleSubmit is not defined

Its all nice if i use "traditional" javascript (e.g. jQuery, console.log), so enqueueing is not the problem. I am pretty new with "modern" javascript (React, Angular...) and the question is surely pretty dumb, but i am looking for a proper way to coding and not only looking for a functional solution.

I am trying to develop a custom gutenberg block. I have a form in save.js:

export default function save() {
return (
    <div {...useBlockProps.save()}>
            <form onSubmit={handleSubmit}></form>
</div>);}

File view.js is defined in block.json ("viewScript": "file:./view.js",)

const handleSubmit = async (event) => {
event.preventDefault();

const formData = new FormData(event.target);
...
};

But when the block renders, it fails.

Uncaught ReferenceError: handleSubmit is not defined

Its all nice if i use "traditional" javascript (e.g. jQuery, console.log), so enqueueing is not the problem. I am pretty new with "modern" javascript (React, Angular...) and the question is surely pretty dumb, but i am looking for a proper way to coding and not only looking for a functional solution.

Share Improve this question edited Dec 10, 2023 at 20:08 Shugui asked Dec 10, 2023 at 18:49 ShuguiShugui 11 bronze badge 1
  • Add export in view.js to export handleSubmit export const handleSubmit = async (event) => { then import handleSubmit in the beginning of save.js page import { handleSubmit } from './save'; – Bikash Waiba Commented Dec 14, 2023 at 23:09
Add a comment  | 

1 Answer 1

Reset to default 1

To achieve your goal:

  • All of your React logic will need to be in your edit.js file and not your save.js file. The save.js file is only for viewing the final data on the WP Admin after you save a post or on the live post.

  • The view.js file can only contain Vanilla JavaScript (from the way you are using it). Then when you save your block, on the saved post WP Admin screen or the live post screen you the React JSX you added in your save.js file will be converted to HTML and your view.js file will need to be Vanilla JavaScript that interacts with this HTML.

Let em know if this makes sense.

本文标签: plugin developmentJavascript function defined in viewjs not reachable from savejs