React 组件和 CSS:同一元素中的项目样式不同



我有一个名为"Badge"的 React 组件,返回一些样式为粗体的文本。

render() {
return (
<div>
<Text weight={'bold'}>
{this.props.label}
</Text>
</div>
)

现在,我在另一个名为"Card"的组件中使用"徽章"。 

因为在徽章组件中,所有文本的样式都为粗体,所以整个句子也是粗体:

return (
<div>
<Badge lable={'This part of the sentence is ' + 'normal font style' + ' and the rest is bold.'}></Badge>
</div>
)

现在,我想以不同的方式设置此元素中的项目的样式:我想从"普通字体样式"中删除粗体样式 - 仅适用于字符串的这一部分。我已经尝试过这种方式,但它不起作用:

<Badge label={'This part of the sentence is ' + <span class=”normalText”>'normal font style'</span> + ' and the rest is bold.'}></Badge>

作为一个绝对的初学者,这个问题让我发疯。有什么想法可以解决这个问题吗?

如果要传递带有html标签的text,则必须以html形式传递所有文本/标签。检查下面的代码。

import React, { Component } from 'react';
import ReactDOM,{ render } from 'react-dom';
import Badge from './Badge';
import './style.css';
class App extends React.Component {
render() {
return (
<div>       
<Badge label="test" /><br/>
<Badge label={'This part of the sentence is ' + 'normal font style' + ' and the rest is bold.'} /><br/>
<Badge label={<>
<span>This part of the sentence is</span> <span className="normalText">'normal font style'</span> <span> and the rest is bold.</span> 
</>}
/>
</div>
);
}
}
render(<App />, document.getElementById('root'));

我为您创建了小演示.
https://stackblitz.com/edit/react-rvuqv6

希望这对你有用!

更合适的系统是将标签值作为徽章的子项。 声明锁屏提醒组件代码,如以下示例所示:

const Badge = props => {
return (
<div className={`badge-class`}>
<Text weight={'bold'}>
{props.children}
</Text>
</div>
)
}

现在像这样调用组件

return (
<div>
<Badge>
This part of the sentence is <span className={`normal-texts`}>normal font style</span> and the rest is bold.
</Badge>
</div>
)

有了这个,您可以在徽章组件,文本,图像等上传递任何类型的子项。

最新更新