javascript - React 组件返回原始 HTML

标签 javascript reactjs jsx

我有一个返回 HTML 表格的 React 组件。

调用方式:<Options list={item} />

这是返回表的功能组件:

const Options = (props) => {

let table = `
<table className="table table-striped table-hover ">
        <thead>
            <tr>
            <th>#</th>
            <th>Option</th>
            <th>Votes</th>
        </tr>
        </thead>
        <tbody>
`

for (let i = 0; i < props.list.options.length; i++){
    table += `<tr>
    <td>${i+1}</td>
    <td>${props.list.options[i].option}</td>
    <td>${props.list.options[i].vote}</td>
    </tr>
    `
}

table += `</tbody></table>`
return table;
}

但是我在屏幕上看到的是:

enter image description here

为什么浏览器没有渲染 HTML?

最佳答案

您正在返回字符串。你应该这样做

    const Options = (props) => {

    let table = 
       (<table className="table table-striped table-hover ">
          <thead>
            <tr>
              <th>#</th>
              <th>Option</th>
              <th>Votes</th>
            </tr>
          </thead>
          <tbody>
             {props.list.options.map((op, i) => {
                return (
                <tr key={i}>
                   <td>{i+1}</td>
                   <td>{op.option}</td>
                   <td>{op.vote}</td>
                </tr>
                )
             })};
          </tbody>
        </table>);

    return table;
  }

关于javascript - React 组件返回原始 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46623136/

相关文章:

javascript - AngularJS 和企业应用程序

javascript - openweathermap API 到 Angular ES6

javascript - .substr() 内的 .length 属性发生变化?

javascript - 如何打开第二个灯箱

javascript - React bootstrap 重复模态组件

javascript - Webpack 3 在 JSX 语法上失败

javascript - 映射到数组后创建动态对象键

javascript - 当您想使用 Link 组件时,外部链接在 Next.js 中不起作用

reactjs - defaultValue 或值不适用于 FormItem ANTD

javascript - 如何确定 React 中的元素滚动位置