簡體   English   中英

如何使用next.js注入動態html元素頁面?

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

如何使用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>
   )
}

結果為null,對於表示沒有任何意義。

問題是,我做對了嗎? 有沒有更好的辦法?

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

這樣做的結果是你返回的字符串必須是有效的HTML(而不是JSX)。 所以請注意我使用了class而不是className

你可以在這里閱讀更多相關信息: https//reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM