css - React 组件和 CSS : style items in the same element differently

标签 css reactjs

我有一个名为“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/

相关文章:

html - 如何去除斑马条纹的边框间距

java - 无法使用 Selenium WebDriver (Firefox) 与输入(角色=组合框)交互

css - 创建特殊效果 CSS box-shadow

javascript - React 上下文 - 'contextType' 未定义

javascript - 如何在reactjs中上传到Firebase存储之前调整图像大小

reactjs - 如何在 React Native android 上使包裹相机的 TouchableOpacity 可点击?

CSS "table-layout: fixed"和由内部内容自动调整宽度的单元格

css - 如何使静态 ionic 列表在 ionic 中可滚动?

reactjs - 流量: Missing type annotation for T

reactjs - 具有 Material UI TextField 的 react-hooks-form 相关字段