如何在 React 中创建阅读更多/更少按钮

在构建 Web 应用程序时,有时我们需要显示一些长文本。在这种情况下,一个聪明的设计是只显示部分文本并添加一个显示更多按钮供用户在需要时展开文本。当文本已展开并完全显示时,有一个 Show Less 按钮可将其折叠。

下面的完整示例向您展示了如何做到这一点。

应用预览

如何在 React 中创建阅读更多/更少按钮

代码

1.创建一个全新的 React 项目:

$ npx create-react-app kindacode-example

会自动生成一堆文件和文件夹。无论如何,我们只关心 2 个文件:src/App.js和src/App.css。

  1. src/App.js中,我们创建了一个名为ExpandableText的可重用组件(我们可以将它放在一个单独的文件中以保持内容井井有条)。该组件可以采用 2 个 props:children(文本)和descriptionLength(初始显示的最大字符数)。这是src/App.js的完整源代码和解释:
// jiyik.com
// src/App.js
import { useState } from 'react';
import './App.css';

// Createa reusable Read More/Less component
const ExpandableText = ({ children, descriptionLength }) => {
  const fullText = children;

  // Set the initial state of the text to be collapsed
  const [isExpanded, setIsExpanded] = useState(false);

  // This function is called when the read more/less button is clicked
  const toggleText = () => {
    setIsExpanded(!isExpanded);
  };

  return (
    <p className='text'>
      {isExpanded ? fullText : `${fullText.slice(0, descriptionLength)}...`}
      <span onClick={toggleText} className='toggle-button'>
        {isExpanded ? 'Show less' : 'Show more'}
      </span>
    </p>
  );
};

// Main App
function App() {
  return (
    <>
      <div className='container'>
        <div className='card'>
          <h1 className='title'>Welcome To jiyik.com</h1>
          <p>
            {/* Only show 120 characters in the beginning */}
            <ExpandableText descriptionLength={120}>
              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut
              egestas mauris. Maecenas leo mauris, accumsan vel velit ac,
              blandit lobortis est. Vivamus in erat ac magna faucibus placerat
              eget non ligula. Aliquam consequat rhoncus turpis a convallis.
              Pellentesque ac sapien rhoncus, congue nibh eget, finibus turpis.
              Aenean volutpat malesuada augue, at lacinia dolor volutpat congue.
              Ut sit amet nunc ac arcu imperdiet iaculis. Mauris sit amet quam
              ut nisi blandit blandit congue nec lorem. Mauris viverra, quam non
              aliquet pellentesque, lorem risus fermentum mi, a mollis turpis
              velit vitae nulla. Proin auctor, elit a rhoncus vulputate, est
              magna facilisis ipsum, non mattis sem odio in neque. Cras at
              ultricies eros. Ut risus turpis, consequat sed auctor nec, rutrum
              id mauris.
            </ExpandableText>
          </p>
        </div>

        <div className='card'>
          <h1 className='title'>Just A Dummy Title</h1>
          <p>
            {/* Show 200 characters in the beginning */}
            <ExpandableText descriptionLength={200}>
              Aliquam maximus, purus vel tempus luctus, libero ipsum consectetur
              purus, eu efficitur mi nunc sed purus. Etiam tristique sit amet
              nisi vel rhoncus. Vestibulum porta, metus sit amet tincidunt
              malesuada, dui sapien egestas magna, quis viverra turpis sapien a
              dolor. Fusce ultrices eros eget tincidunt viverra. Ut a dapibus
              erat, vel cursus odio. Phasellus erat enim, volutpat vel lacus eu,
              aliquam sodales turpis. Fusce ipsum ex, vehicula tempor accumsan
              nec, gravida at eros. In aliquam, metus id mollis interdum, nunc
              sem dignissim quam, non iaculis tortor erat nec eros. Nunc
              sollicitudin ac dolor eget lobortis. Aenean suscipit rutrum dolor
              in euismod. Curabitur quis dapibus lectus. Mauris enim leo,
              condimentum ac elit sit amet, iaculis vulputate sem.
            </ExpandableText>
          </p>
        </div>
      </div>
    </>
  );
}

export default App;

CSS 是本次演示的重要组成部分。删除src/App.css中的所有默认代码并添加以下内容:/* src/App.css */

.container {
  width: 80%;
  margin: 50px auto;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.card {
  width: 43%;
  padding: 15px 20px;
  background: #fffde7;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2);
  border-radius: 10px;
}

.text {
  width: 100%;
}

/* Style the read more/less button */
.toggle-button {
  margin-left: 7px;
  color: blue;
  cursor: pointer;
}

.toggle-button:hover {
  color: red;
  text-decoration: underline;
}

完成。现在让我们的应用程序启动并运行,然后转到 http://localhost:3000 进行测试。