首页 > 解决方案 > 接受不同的 html 模板数据作为 reactjs 组件的选项

问题描述

在 reactjs 中,我如何使用模板 html 数据呈现组件?

class Options extends React.Component {
    render() {
        const othList = [];

        [1, 2, 3, 4, 5].forEach((t) => {
            othList.push(t);
        });

        return othList;
    }
}

如何传递 html 数据并使用提供的 html 作为模板?

<Options><div></div></Options>

所以上面将呈现 5 个 div 主要是 1 个等。或者 <Options><td></td></Options>将呈现 5 个 td

谢谢

标签: javascripthtmlreactjscomposition

解决方案


危险地设置内部 html

如果您将 html 作为字符串,则可以使用此方法在 react 中将其设置在组件中。

从文档

function MyComponent() {
  return <div dangerouslySetInnerHTML={{__html: 'First &middot; Second'}} />;
}

在您的代码中(假设 othList 是一个 html 模板数组)

class Options extends React.Component {
    render() {
        const othList = [];

        [1, 2, 3, 4, 5].forEach((t) => {
            othList.push(t);
        });

        let activeTemplateIndex = 0;

        return <div dangerouslySetInnerHTML={{__html: othList[activeTemplateIndex]}} />;
    }
}

推荐阅读