我有一个名为“Badge”的 React 组件,返回一些样式为粗体的文本。
render() {
return (
<div>
<Text weight={'bold'}>
{this.props.label}
</Text>
</div>
)
现在,我在另一个名为“Card”的组件中使用“Badge”。
因为在 Badge 组件中所有文本都是粗体样式,所以整个句子也是粗体:
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
希望这对你有用!
关于css - React 组件和 CSS : style items in the same element differently,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57849569/