如何在 React 中划掉(删除线)文本

使用 textDecoration 属性在 React 中为文本添加删除线,例如 <span style={{textDecoration: ‘line-through’}}>. text-decoration CSS 属性设置文本装饰线条的外观。

const App = () => {
  return (
    <div>
      <h2>
        <span style={{textDecoration: 'line-through'}}>Hello</span> world
      </h2>
    </div>
  );
};

export default App;

如果我们需要在单击时删除元素,请查看我的另一篇文章 – 在 React 中单击时删除(删除线)文本

我们使用 text-decoration 属性来划掉 React 中的文本。

请注意 ,当指定为内联样式时,多词属性是驼峰式的。

内联样式中的第一组花括号标志着表达式的开始,第二组花括号是包含样式和值的对象。

<span style={{textDecoration: 'line-through'}}>Hello</span> world

当元素的 textDecoration 属性设置为 line-through 时,它的文本会被划掉。

如果我们需要经常这样做,可以将 span 元素提取到呈现其子项的组件中。

function StrikethroughText({children}) {
  return <span style={{textDecoration: 'line-through'}}>{children}</span>;
}

const App = () => {
  return (
    <div>
      <h2>
        <StrikethroughText>Hello</StrikethroughText> world
      </h2>
    </div>
  );
};

export default App;

此代码示例实现了相同的结果。 无论我们在 StrikethroughText 组件的开始标签和结束标签之间传递什么,都会将其文本划掉。

另一种解决方案是在全局 css 文件中定义删除线类。

.strikethrough {
  text-decoration: line-through;
}

下面是我们如何导入 App.css 文件并使用删除线类。

import './App.css';

const App = () => {
  return (
    <div>
      <h2>
        <span className="strikethrough">Hello</span> world
      </h2>
    </div>
  );
};

export default App;

这种方法使我们能够通过在全局 css 文件中定义常用样式来重用它们。

在 index.js 文件中导入全局 css 文件是最佳实践,因为这样它们不仅会在安装某些组件时被加载。