如何映射对象中的字符串,其中空字符串被视为空行,并且每个字符串仅限于一行


{
"ptr0": [
"Interviewer: Nancy Carolyn Camp Foster (NF)",
"",
"Interviewee: Edith Mills (EM)",
"",
"NF: Well it's kind of interesting to observe how students have turned out who've",
"gone through Bristow schools. We lose track, we don't really realize and",
"",
"Other Persons: Lucy Mae Mills (LM) Unknown Woman (WS)"
]
}

我正试图在浏览器中的jsx中映射上面的objecttrans对象ptr0,我希望对象中的空字符串被视为空行,并且对象中的每个字符串都被限制在一行,我试图在浏览器jsx:中显示这样的内容

采访者:Nancy Carolyn Camp Foster(NF(

受访者:Edith Mills(EM(

NF:观察学生们是如何通过布里斯托学校的,这有点有趣。我们迷失了方向,我们没有真正意识到,

其他人:Lucy Mae Mills(LM(未知女性(WS(

我称之为转录组件的组件

<Transcript
transcript={objecttrans.ptr0.map(pt=>{          
return   pt               
})}
/>

转录组分

return (
<>
<div className="content">
<p>{props.transcript}</p>
</div>
</>
);

您的代码似乎在做您希望它做的事情。如果您的问题是没有显示新行,那么当字符串为空时,您可以只返回一个br元素。类似于:

objecttrans.ptr0.map(pt => pt || <br />

const Transcript = props => <div className="content">
<p>{props.transcript}</p>
</div>;

const objecttrans = {
"ptr0": [
"Interviewer: Nancy Carolyn Camp Foster (NF)",
"",
"Interviewee: Edith Mills (EM)",
"",
"NF: Well it's kind of interesting to observe how students have turned out who've",
"gone through Bristow schools. We lose track, we don't really realize and",
"",
"Other Persons: Lucy Mae Mills (LM) Unknown Woman (WS)"
]
};
ReactDOM.render(
<Transcript
transcript={objecttrans.ptr0.map(pt => pt || <br />)}
/>, document.body
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

使用换行符将行数组连接到单个字符串中:

const text = lines.join('n');

然后将文本放入预先格式化的文本元素<pre>中,而不是段落元素<p>中,并按照您的意愿进行样式设置。

const lines = [
"Interviewer: Nancy Carolyn Camp Foster (NF)",
"",
"Interviewee: Edith Mills (EM)",
"",
"NF: Well it's kind of interesting to observe how students have turned out who've",
"gone through Bristow schools. We lose track, we don't really realize and",
"",
"Other Persons: Lucy Mae Mills (LM) Unknown Woman (WS)",
];
const text = lines.join('n');
document.querySelector('pre').textContent = text;
<pre></pre>

最新更新