在 React.js 中实施阅读更多 link

Implementing a Read More link in React.js

我正在尝试实现 Read More link,它会展开以显示 单击后显示更多文本。我正在尝试以 React 方式执行此操作。

<!--html-->
<div class="initialText">
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. 
  <a>
    Read More
  </a>
</div>

<div class="fullText">
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>

/* JavaScript */
/* @jsx DOM */
var component = React.createClass({

  getInitialState: function() {
    return {
      expanded: false
    };
  },

  expandedText: function() {
    this.setState({
      expanded: true
    });       
  },

  render: function() {
    return (
      <div>

      </div>
    );
  }

});

我是 React 新手。我不确定如何处理渲染方法中的所有内容。我如何在纯 React 中实现此功能?

所以基本上你想根据状态显示额外的 div 属性 'expanded'.

您可以有条件地创建组件。如果你不想要一个组件,你可以 return null。 我只会有一个像这样的小方法:

var component = React.createClass({
    getInitialState: function() {
        return {
           expanded: false
       };
    },

    expandedText: function() {
        this.setState({
            expanded: true
        });       
    },

    getMoreTextDiv: function() {
        if (this.state.expanded) {
          return <div> My extended content </div>;
        } else {
          return null;
        }
    }
});

你的渲染函数应该变成:

render: function() {
     var expandedDiv = this.getMoreTextDiv();
     return (
         <div>
             <a onClick={this.expandedText}>Read more</a>
             { expandedDiv }
         </div>
     );
}

每次调用 setState() 时都会使用新状态触发 render()

如果 expanded 为 false,您将 return null 作为一个组件,这基本上意味着什么都没有。所以什么也不会显示。

当您单击 link 时,它会更新您的状态和扩展值,因此您将 return 一个 div 作为一个组件并显示出来。

我认为阅读 this 是一个好的开始。 这是一篇非常棒的文章,解释了渲染的基本原理,以及 link with state。

您还应该确保您了解这种小示例http://jsfiddle.net/3d1jzhh2/1/,以了解状态和渲染如何相互 link。

您的方向基本正确。如此处的反应文档所述: https://facebook.github.io/react/tips/if-else-in-JSX.html

它只是使用了一个经典的 if 和一个变量,像这样:

render: function() {
    var expandedContent;
    if (this.state.expanded) {
        expandedContent = <div>some details</div>;
    }

    return (
       <div>
           <div>Title or likewise</div>
           {expandedContent}
       </div>
    );
}

我知道我回答这个问题有点晚了,但为什么不使用 2 个字符串而不是只使用 1 个字符串呢?

查看这个 npm 包 https://www.npmjs.com/package/react-simple-read-more 它会解决问题。

如果您对代码感兴趣:https://github.com/oztek22/react-simple-read-more/blob/master/src/string-parser.jsx

你可以试试 read-more-react 库,link:https://www.npmjs.com/package/read-more-react

npm install --save read-more-react
import ReadMoreReact from 'read-more-react';


<ReadMoreReact 
        text={yourTextHere}
        min={minimumLength}
        ideal={idealLength}
        max={maxLength} 
/>

再一次迟到的回答,但也许有人需要它。

所以基本上你只需要一个组件来接收你想要显示的文本。 然后您将使用 useState 钩子来设置文本长度的值 - 是否需要显示短版或长版,并在结束一个将在短文本和长文本之间切换的函数。

代码示例:

import React, { useState } from 'react';

const ReadMore = ({text}) => {
  const [isReadMore, setIsReadMore] = useState(true);
  const toggleReadMore = () => {setIsReadMore(!isReadMore)};

  return (
    <p className='testimonials__quote__text'>
      {isReadMore ? text.slice(0, 150): text }
      // condition that will render 'read more' only if the text.length is greated than 150 chars
      {text.length > 150 &&
        <span onClick={toggleReadMore}>
          {isReadMore ? '...read more' : ' ...show less'}
        </span>
      }
    </p>
  )
}

export default ReadMore;

这是 React Js 中的完整解决方案:

调用组件:

<TeamCard description="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s." limit={150}/>

组件:

const TeamCard = ({ description, limit }) => {
  const [showAll, setShowAll] = useState(false);
  return (
    <p className="text-center text-white text-base pt-3 font-normal pb-5">
      {description.length > limit ? (
        <div>
          {showAll ? (
            <div>
              {description}
              <br />
              <button
                onClick={() => setShowAll(false)}
                className="text-primary"
              >
                Read Less
              </button>
            </div>
          ) : (
            <div>
              {description.substring(0, limit).concat("...")}
              <br />
              <button onClick={() => setShowAll(true)} className="text-primary">
                Read More
              </button>
            </div>
          )}
        </div>
      ) : (
        description
      )}
    </p>
  );
};
export default TeamCard;