我有一个具有name
属性的对象数组,该对象数组带有一个带有h1
元素标签的字符串。当我尝试将数据绑定到表td时,它显示为纯文本而不是html。
此处复制的示例:https://stackblitz.com/edit/react-table-example-2rcaug?file=index.js
class App extends React.Component {
constructor() {
this.state = {
data:
[
{
"id": 1,
"name": "<h1>Foo</h1>",
"age": "20"
},
{
"id": 2,
"name": "<h1>Bar</h1>",
"age": "30"
},
{
"id": 3,
"name": "<h1>test</h1>",
"age": "40"
}
]
}
}
componentDidMount(){
let test = [...this.state.data]
test.map((col, i) => {
var wrapper = document.createElement("div");
wrapper = col.name;
test[i].name = wrapper
console.log(wrapper)
});
this.setState({data : test})
}
render() {
return (
<div>
<Header />
<table>
<tbody>
{this.state.data.map((person, i) => <TableRow key={i} data={person}
/>)}
</tbody>
</table>
</div>
);
}
}
class Header extends React.Component {
render() {
return (
<div>
<h1>Header</h1>
</div>
);
}
}
class TableRow extends React.Component {
render() {
return (
<tr>
<td>{this.props.data.id}</td>
<td>{this.props.data.name}</td>
<td>{this.props.data.age}</td>
</tr>
);
}
}`
答案 0 :(得分:0)
您有两种选择 1.从数据名称中删除h1
this.state = {
data:
[
{
"id": 1,
"name": "Foo",
"age": "20"
},
{
"id": 2,
"name": "Bar",
"age": "30"
},
{
"id": 3,
"name": "test",
"age": "40"
}
]
}
}
class TableRow extends React.Component {
render() {
return (
<tr>
<td>{this.props.data.id}</td>
<td><h1>{this.props.data.name}</h1></td>
<td>{this.props.data.age}</td>
</tr>
);
}
}`
class TableRow extends React.Component {
render() {
return (
<tr>
<td>{this.props.data.id}</td>
<td dangerouslySetInnerHTML = {this.props.data.name} />
<td>{this.props.data.age}</td>
</tr>
);
}
}
答案 1 :(得分:0)
您可以使用 dangerouslySetInnerHTML 进行此操作,请查看
但是,我不建议这样创建 DOM ,而是让您的状态仅保留如下所示的值,并让标记位于TableRow
组件内部
this.state = {
data:
[
{
"id": 1,
"name": "Foo",
"age": "20"
},
{
"id": 2,
"name": "Bar",
"age": "30"
},
{
"id": 3,
"name": "test",
"age": "40"
}
]
}
}
TableRow组件:
class TableRow extends React.Component {
render() {
return (
<tr>
<td>{this.props.data.id}</td>
<td><h1>{this.props.data.name}</h1></td>
<td>{this.props.data.age}</td>
</tr>
);
}
}