我有一个数据对象,我正在从CMS中提取数据来创建博客,并通过content对象进行映射,以便呈现博客的主体。
我创建了一个三元操作符,从本质上说,如果文本行有一种类型的“强”,则使字体粗体,否则,如果它有一种类型的“超链接”,那么将文本块作为标签中的链接。
我遇到的问题是,一些文本是“粗体”和“超链接”,所以它是两次呈现这个句子,我如何确保当类型都是‘粗体’和‘超链接’时,它只呈现一次?
我的数据就是这样的:

下面是我的文件,在这里我会在前端返回这些数据:
<div className='text-left mt-12 text-white'>
<h1 className='text-5xl mb-4 font-header text-blue-500'>
{RichText.asText(data.title)}
</h1>
{data.content.map((t, i) => {
return (
<>
{!t.spans[0] && (
<p className={`text-lg mt-6 opacity-80 ${t.type}`}>
{t.text}
</p>
)}
{t.spans.map((item) =>
item.type === 'strong' ? (
<p className={`text-xl mt-6 font-bold ${t.type}`}>
{t.text}
</p>
) : item.type === 'hyperlink' ? (
<a
href={item.data.url}
target='_blank'
className={`text-lg opacity-80 mt-6 text-blue-500 ${t.type}`}>
{t.text}
</a>
) : item.type === 'list-item' ? (
<ul className='list-disc'>
<li className='text-lg mt-4 text-white'>{t.text}</li>
</ul>
) : (
<p
className={`text-lg opacity-80 mt-6 font-bold ${t.type}`}>
{t.text}
</p>
)
)}
</>
);
})}
</div>我肯定这很简单,但我想知道处理这种事情的最佳方法是什么?
提前感谢!
发布于 2021-11-10 16:06:05
不要在类型上进行逻辑切换。
试着做这样的事情:
const styleProps = spans.reduce((acc, span) => {
if (span === 'strong'){
acc['font-weight'] = 'bold';
}
if (span === 'something-else'){
acc['some-css-prop'] = 'some-value';
}
...
return acc;
}, {})然后,您将有一个累加器(styleProps),其中包含所有必要的支持,以对组件进行样式化。
<YourComponent className="my-constant-class-name" style={{...styleProps}} />你可以概括这个想法:
例如。
const MyComponentProps = spans.reduce((acc, span) => {
if (span === 'strong'){
acc.style['font-weight'] = 'bold';
}
if (span === 'hyperlink'){
acc['href'] = 'www.example.com';
}
...
return acc;
}, {});而且还
let MyComponent = null;
switch(type){
case 'hyperlink':
MyComponent = (props) => <a {...props} />;
break;
case 'text':
MyComponent = (props) => <p {...props} />;
break;
case 'bullet':
MyComponent = (props) => <li {...props} />;
break;然后
<MyComponent {...MyComponentProps} />https://stackoverflow.com/questions/69915975
复制相似问题