【问题标题】:Accept different html template data as options for reactjs component接受不同的 html 模板数据作为 reactjs 组件的选项
【发布时间】:2020-04-21 11:55:10
【问题描述】:

在 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 个等。 或者 &lt;Options&gt;&lt;td&gt;&lt;/td&gt;&lt;/Options&gt; 将渲染 5 个 td

谢谢

【问题讨论】:

    标签: javascript html reactjs composition


    【解决方案1】:

    危险地设置内部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]}} />;
        }
    }
    

    【讨论】:

    • 有没有办法使用作为 props.children 传递的 html 作为 html 模板并返回绑定到 html 的数据?因此,如果我通过 我希望 Options 组件呈现 5 个 td 的?
    猜你喜欢
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 2021-03-29
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多