如何简化模板中的条件以避免多次重复

How to simplify the conditions in template to avoid multiple repetitions

我有一个场景,比如显示文本以及添加 class 在一起。看起来我需要多次添加几乎相同的元素。对于这种情况,正确的方法是什么?

这是我的模板:

<span><a className={this.state.showMore ? 'active' : ''} onClick={this.showMore}>{this.state.showMore ? 'read less' : 'read more'}</a></span>

我在里面添加了 state showMore a 标签和 text。有什么简单的方法可以跨页面处理相同的情况吗?

提前致谢。

{this.state.showmore ? 
<span><a className={'active'} onClick={this.showMore}>read less</a></span> 
:
<span><a onClick={this.showMore}>read more</a></span>
}

应该是一种更易读、更清晰的方式。基本上当你有超过 1 个东西取决于相同的条件时,把条件放在外面是我的方法!

我会创建一个组件来处理阅读更多,如果有的话,从使用它的地方传递道具,所以相同的功能在我的应用程序中是相同的,如果有任何改进我可以通过它一次性处理地点。

这是一个demo

EX:功能组件

export const ReadMore = ({ text, truncateLength = 10 }) => {
  const [showMore, setShowMore] = useState(false);

  const getText = () => {
    if (showMore) {
      return text;
    }

    const truncatedText = text.substring(0, truncateLength);
    if (text.length > truncateLength) {
      return `${truncatedText}...`;
    }

    return truncatedText;
  };

  return (
    <span>
      {getText()} &nbsp;
      <a
        className={showMore ? "active" : ""}
        onClick={() => setShowMore(!showMore)}
      >
        {text.length > truncateLength && (showMore ? "read less" : "read more")}
      </a>
    </span>
  );
};

并像这样使用道具可以是:

  • text: 是应该少读或多读的文字。

  • truncateLength:如果文本长度为 更大的可选道具,如果没有提供 ReadMore 组件默认将值设置为 10,(检查 props ReadMore)

<ReadMore
    text="this is the text that should do the react-more and read-less"
    truncateLength={10}
/>