如何将动态 html 元素注入到带有 next.js 的页面?

how can injection dynamic html element to page with next.js?

如何动态注入html元素到next.js页面?这些元素未知类型(输入、复选框、img、...)。此元素用 api 指定 return 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>
   )
}

结果为空,对演示没有任何意义。

问题是,我做对了吗?有没有更好的方法?

发生的事情是,在 getInitialprops 中从服务器到客户端的 props 传输过程中,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>
        );
    }
}

这里的问题是你 return 的字符串必须是有效的 HTML (不是 JSX)。所以请注意我使用 class 而不是 className

您可以在此处阅读更多相关信息:https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml