我正在嘗試使用 JSON 文件在 Gatsby 中動態創建頁面。在該文件中,我定義了應該在頁面中呈現的組件。我遵循了 Gatsby 的文檔,但是,它沒有我想要的。所以我嘗試通過讀取 JSON 文件并遍歷其中的組件并使用 React.createElement() 創建它們來創建頁面。最后,我得到了一組 react 組件,我將這些組件傳遞給了 createPage 方法的上下文對象中的 children prop 到模板頁面組件。這是解決這個想法的正確方法嗎?它在 Gatsby 中是否可行?我認為可以說我嘗試過動態導入并且效果很好,但我正在嘗試找到一種方法,我不必將所有組件都轉儲到一個文件夾中。我有這個項目的 Github 倉庫。 https://github.com/ahmedalbeiruti/Gatsby-dynamic-pages這是代碼的主要部分:gatsby-node.jsexports.createPages = ({actions})=>{ const {createPage} = actions const resutl = componentsRenderer(data.page.layout.columns) createPage({ path: data.page.name, component: path.resolve('./src/template/page.js'), context:{ children: resutl } })}const componentsRenderer = components => { return components.map(component => { let children = [] if (component.children){ children = componentsRenderer(component.children) } const element = require(`${__dirname}/${component.path}`) return React.createElement(element, Object.assign({},{key: component.key},{...component.props}),children) });}數據/樣本頁面無道具.json{ "page":{ "name": "about", "layout":{ "columns": [ { "key":"column_1", "name": "Column", "path": "/src/components/layouts/column.jsx", "children":[ { "name": "FirstComponent", "path": "/src/components/custom/first-component.jsx", "key": "first_component_1" } ] },
如何從 JSON 文件在 Gatsby 中創建頁面?
慕容708150
2021-08-26 16:38:03