在Gutenberg前端使用React。

huangapple go评论64阅读模式
英文:

Using React in Gutenberg frontend

问题

所以这是一个相当简单的问题,我在互联网上搜索了很多。我发现还有很多人不明白为什么这样的功能还没有可用。

我需要在我的 Gutenberg 区块的前端(通常是 save.js 文件)上使用 React。有人已经找到了解决这个问题的方法吗? Gutenberg 开发团队是否正在研究解决方案或可能的新功能?

英文:

So it's a pretty simple question and I've searched a lot on the internet. I found out there's a lot of people still wondering why a feature like this is not already available.

I need to use React on the frontend (typically the save.js file) of my Gutenberg block. Has anyone found a solution to this problem yet? Is the Gutenberg dev team looking into a solution or possible new features to this product?

答案1

得分: 1

我之前有同样的问题,所以想在这里分享我的答案,以防有人需要。

基本上,save 函数只返回一个 HTML 字符串,该字符串将被保存到数据库并在前端呈现,因此不要期望它会处理其中的任何逻辑功能。

解决方法是在前端附加一个 JavaScript 文件,一旦在前端呈现,它就会将 React 事件与 DOM 元素关联起来。
对于附加到块的任何属性,您还需要获取所有属性并将它们放入 React 元素的 props 中。

这是一个示例,您可以查看一下
https://github.com/trykoszko/gutenberg-block-hydration-example

英文:

I had a same question before so just wanna share my answer here just in case if anyone need it.

basically, the save function just returns a html string which will be saved to DB and rendered on front end, so don’t expect it would handle any logical function within it.

A solution for this one is you need to attach a js file on frontend, which will hydrate the react events to the dom element once it is rendered on front end side.
For any attributes attached to the block, you also need to get all of them and put to the props of the react element.

This is an example that you can take a look
https://github.com/trykoszko/gutenberg-block-hydration-example

huangapple
  • 本文由 发表于 2023年5月29日 06:04:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76353771.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定