Hoo*_*eri 1 node.js reactjs next.js
如何动态注入 html 元素到 next.js 页面?这些元素未知类型如(输入,复选框,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":[]
}]
Run Code Online (Sandbox Code Playgroud)
我的尝试是:
[{
"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":[]
}]
Run Code Online (Sandbox Code Playgroud)
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
}
})
Run Code Online (Sandbox Code Playgroud)
结果为空,表示没有任何意义。
问题是,我做对了吗?有没有更好的办法?
发生的情况是,在将 props 从服务器传输到客户端的过程中getInitialprops,JSON 被序列化,因此函数并未真正序列化。见https://github.com/zeit/next.js/issues/3536
最好的办法是将测试数据转换为一串 HTML 数据并使用dangerouslySetInnerHTML. 一个例子是:
class TestComponent extends React.Component {
static async getInitialProps() {
const text = '<div class="homepsage">This is the homepage data</div>';
return { text };
}
render() {
return (
<div>
<div className="text-container" dangerouslySetInnerHTML={{ __html: this.props.text }} />
<h1>Hello world</div>
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
问题在于您返回的字符串必须是有效的 HTML(不是 JSX)。所以请注意我用class而不是className
您可以在此处阅读更多相关信息:https : //reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml
| 归档时间: |
|
| 查看次数: |
8655 次 |
| 最近记录: |