我想在javascript数组上使用join((方法,但是我想使用html标签加入((。
我想做类似:
的事情class Page extends React.Component {
render() {
<p>
{this.props.the_form['candidate_ids'].map((val,idx) => {
return this.getCandidateName(val);
}).join('<br/>')}
</p>
}
}
它逃脱了标签,而不是渲染新线路。
我正在使用React,Webpack和Babel。
我必须添加它,因为dangerouslySetInnerHTML
并加入长字符串并不是真正的反应方式,并且有点误导。另外,您缺少映射项目上的key
//import Fragment
import { Fragment, Component } from "react"
class Page extends Component {
const ids = this.props.the_form['candidate_ids'];
render() {
<p>
{ids.map((val, idx) => {
const name = this.getCandidateName(val);
return (
<Fragment key={`${name}${idx}`}>
{name}
{idx < ids.length - 1 && <br />}
</Fragment>
);
})}
</p>
}
}
(已更新以删除尾声<br/>
(。
这是一个可能的替代版本,没有<br/>
's:
class Page extends Component {
const ids = this.props.the_form['candidate_ids'];
render() {
<p>
{ids.map((val, idx) => {
const name = this.getCandidateName(val);
return (
<span key={`${name}${idx}`} style={{display: 'block'}}>
{name}
</span>
);
})}
</p>
}
}
您的代码很好。假设这里没有框架,我唯一指出的是您需要使用innerHTML
功能
var mArray =[ 'line 1', 'line 2'];
document.body.innerHTML = mArray.map((val,idx) => { return `sometext: <strong>${val}</strong>`; }).join('<br/>')
更新:
由于您使用的是React,因此需要使用dangerouslySetInnerHTML
class Page extends React.Component {
render() {
const html = this.props.the_form['candidate_ids'].map((val,idx) => {
return this.getCandidateName(val);
}).join('<br/>')
return <p dangerouslySetInnerHTML={{__html:html}}></p>
}
}
但是,由于您使用的是JSX,因此您不需要使用字符串和危险steinnerhtml。您也可以使用JSX构成您的DOM:
class Page extends React.Component {
render() {
const {the_form} = this.props;
const dom = the_form['candidate_ids'].map((val,idx) => {
return (
<>
{this.getCandidateName(val)}
{idx+1 < the_form['candidate_ids'].length ? </br> : null}
</>
);
}))
return (<p>{dom}</p>);
}
}
文档:https://reactjs.org/docs/dom-elements.html#dangerlysetlysetinnerhtml