我正在返回一个输出列表的映射,并将其存储在带有html和文本的状态下,该列表将传递给错误组件。问题是列表显示为对象,而html显示为原始文本,而不进行翻译。
设置以下代码并将其传递给组件
let fwobjectList = fwobject.map(function(name, index) {
console.log(name.id);
console.log(name);
console.log(index);
return <li key={index}>{name.id}</li>;
});
this.setState({
showError: true,
errorMsg: `You cannot delete rows where FW Object names have been used. Please unselect row id's<ul>' + ${fwobjectList} + '</ul>`
});
组件在渲染器中调用错误模式
return (
<div className="container-fluid">
...
<ModalError
title={this.state.errorTitle}
body={this.state.errorMsg}
show={this.state.showError}
handleCloseError={this.handleCloseError}
/>
...
)
我的渲染函数处于错误模式。
render(){
let title = 'Error';
let body = 'Unexpected error occured';
if(this.props.title.length > 0){
title = this.title.body;
}
if(this.props.body.length > 0){
body = this.props.body;
}
return (
<Modal
id="myModalError"
className="modal fade"
role="dialog"
show={this.props.show}
>
<Modal.Header closeButton className="modal-header alert alert-danger">
<Modal.Title>{title}</Modal.Title>
</Modal.Header>
<Modal.Body>
{body}
</Modal.Body>
<Modal.Footer>
<Button onClick={this.handleCloseError}>Close</Button>
</Modal.Footer>
</Modal>
);
}
我在浏览器中看到的输出是
"You cannot delete rows where FW Object names have been used. Please unselect row id's<ul>' + [object Object] + '</ul>"
我要打印以下内容
"You cannot delete rows where FW Object names have been used. Please unselect row id's
- 123
- 234
- 456
"
更新
如果我通过此链接Insert HTML with React Variable Statements (JSX)使用示例,则会得到以下信息
You cannot delete rows where FW Object names have been used. Please unselect row id's
' +
3043
+ '
更新2
我设法做fwobjectIds.join().toString()
,但这在我不希望出现的逗号之间留下了逗号。如何删除逗号。
You cannot delete rows where FW Object names have been used. Please unselect row id's
3043
,
3042
答案 0 :(得分:1)
您可以这样实现:
let ids = []
let fwobjectList = fwobject.map(function(name, index) {
ids.push(`<li>${name.id}</li>`)
return <li key={index}>{name.id}</li>;
});
this.setState({
showError: true,
errorMsg: `You cannot delete rows where FW Object names have been used.
Please unselect row id's<ul> ${ids.join()} </ul>`
// no need to concatenate when using template literal above
});
答案 1 :(得分:0)
请记住,您的errorMsg
是一个字符串,而不是组件。您可以走by using dangerouslySetInnerHtml
路线,但是,顾名思义,这不是最好的主意。
我认为最好的做法是将要以错误模式输出的值编码为 state ,然后在render分支中渲染这些值显示错误。
this.setState({ showError: true, rowIds: fwObject.map(o => o.name) })
…
<ErrorModal>
<p>You cannot…</p>
<ul>
{ rowIds.map(r => <li>{r}</li>) }
</ul>
</ErrorModal>
我想您想要一些通用错误弹出窗口。在那种情况下,您的方法可能必须有所不同,但是问题是您是否需要它™