【发布时间】:2023-03-05 03:04:01
【问题描述】:
如何用 next.js 动态注入 html 元素到页面?这些元素未知类型,如(输入,复选框,img,...)。这个元素用 api 指定,返回 json 类型如下:
[{
"id":"rooms",
"title":"Rooms",
"order":1,
"type":"string",
"widget":"select",
"data":[{
"Id":18,
"ParentId":null,
"Title":"One",
"Level":null,
"Childrens":[]
},
{"Id":19,
"ParentId":null,
"Title":"Two",
"Level":null,
"Childrens":[]
},
{"Id":20,
"ParentId":null,
"Title":"Three",
"Level":null,
"Childrens":[]
}]
},
{
"id":"exchange",
"title":"Exchange",
"order":0,
"type":"boolean",
"widget":"checkbox",
"data":[]
}]
我的尝试是:
Index.getInitialProps = async function({req, query}) {
const res= await fetch('url api')
var elements= await res.json()
var test = () => (
<div>
{...... convert json to html elements.......}
</div>
)
return {
test
}
})
function Index(props) {
return(
<a>
{props.test}
</a>
)
}
结果为空,对演示没有任何意义。
问题是,我做对了吗?有没有更好的办法?
【问题讨论】: