【问题标题】:Insert custom React component into a String variable with html content将自定义 React 组件插入到带有 html 内容的 String 变量中
【发布时间】:2020-12-29 03:16:48
【问题描述】:

我有一个包含如下 HTML 标签的字符串:

<div class="header">Hello!</div>
<div class="body">How are you?</div>
<div class="footer">Good bye!</div>

我需要用我的自定义反应组件替换 &lt;div class="body"&gt;How are you?&lt;/div&gt;。 我的反应组件使用从 API 动态获取的数据显示内容。 例如:

import React, { useState } from 'react';
import axios from 'axios';

export default function App(){
    const [books, setBooks] = . useState(null);

    const apiURL = "https://www.anapioficeandfire.com/api/books?pageSize=30";

    const fetchData = async () => {
        const response = await axios.get(apiURL)

        setBooks(response.data) 
    }

    return (
        <div>
           {books.map((book, index) => {
                return <p key={index}>{book.title}</P>
           })}
        </div>
    )
}

如何将 html 字符串替换为 react 组件并同时渲染 html 标签和字符串中的新组件?

【问题讨论】:

    标签: javascript html reactjs


    【解决方案1】:

    使用dangerouslySetInnerHTML

    <div dangerouslySetInnerHTML={html} /> 
    
    

    【讨论】:

      【解决方案2】:

      您可以使用dangerouslySetInnerHTMLcheck docs here

        return (
              <div>
                 {books.map((book, index) => {
                      return  <div key={index} dangerouslySetInnerHTML={{__html: book.title}}></div>
                 })}
              </div>
          )    
      

      【讨论】:

      • 我的问题是将反应组件插入&lt;div class="body"&gt;..&lt;/div&gt;。 React 组件本身运行良好。
      • &lt;div class="body"&gt;How are you?&lt;/div&gt; 在哪里,写的
      • 我已使用 readfilesync 函数将 HTML 文件作为字符串读取。 &lt;div class="body"&gt;How are you?&lt;/div&gt; 是该字符串的一部分。我需要将 react 组件插入到 div 中。 PS:我想在 Next.js 中做到这一点
      猜你喜欢
      • 2020-09-17
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      • 2022-08-21
      • 1970-01-01
      • 2022-10-16
      • 2023-04-02
      相关资源
      最近更新 更多