【问题标题】:how can injection dynamic html element to page with next.js?如何使用 next.js 将动态 html 元素注入页面?
【发布时间】: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>
   )
}

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

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

【问题讨论】:

    标签: node.js reactjs next.js


    【解决方案1】:

    发生的情况是,在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>
            );
        }
    }
    

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

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

    【讨论】:

    • 谢谢它非常有用。但是,这是常用的注入方式吗?
    • 我不会说这是首选标准。确实没有goto标准。如果需要,您还可以返回 json 数据并将其解析为真正的 JSX
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 2012-12-28
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    相关资源
    最近更新 更多