简体   繁体   English

在 React.js 中实现阅读更多链接

[英]Implementing a Read More link in React.js

I am trying to implement a Read More link, which expands to show more text after a click.我正在尝试实现一个Read More链接,该链接会在单击后展开以显示更多文本。 I am trying to do this the React way.我正在尝试以 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>
    );
  }

});

I am new to React.我是 React 的新手。 I am not sure how to handle everything inside the render method.我不确定如何处理渲染方法中的所有内容。 How can I implement this functionality in pure React?我如何在纯 React 中实现此功能?

So basically you want to display an extra div depending on the state property 'expanded'.所以基本上你想根据状态属性'expanded'显示一个额外的div。

You can create a component conditionally.您可以有条件地创建组件。 If you don't want a component you can just return null.如果你不想要一个组件,你可以只返回 null。 I would just have a small method like:我只会有一个小方法,如:

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;
        }
    }
});

and your render function should become:你的渲染功能应该变成:

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

Each time you call setState() you trigger render() using the new state.每次调用setState()都会使用新状态触发render()

If expanded is false you are going to return null as a component, which means basically, nothing.如果expanded 为false,您将返回null 作为组件,这意味着基本上什么都没有。 So nothing will be displayed.所以什么都不会显示。

When you click on your link it will update your state and the expanded value, so you will return a div as a component and it will be displayed.当您单击链接时,它会更新您的状态和扩展值,因此您将返回一个 div 作为组件并显示出来。

I think a good start would be to read this .我认为阅读这篇文章是一个好的开始。 This is a really great article and explains how render basically works, and the link with state.这是一篇非常棒的文章,解释了渲染的基本工作原理,以及与状态的链接。

You should also make sure you understand this kind of small example http://jsfiddle.net/3d1jzhh2/1/ to see how state and render are linked with each other.您还应该确保您了解这种小示例http://jsfiddle.net/3d1jzhh2/1/以了解状态和渲染是如何相互关联的。

You can try the read-more-react library, link: https://www.npmjs.com/package/read-more-react可以试试read-more-react库,链接: 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} 
/>

Late answer once again, but maybe someone will need it.再次迟到回答,但也许有人需要它。

So basically you just need one component that will receieve the text you want to display.所以基本上你只需要一个组件来接收你想要显示的文本。 Then you will use the useState hook that will set the value of text length - does it need to be short or long version displayed, and on the end one function that will toggle between short and long version of the text.然后,您将使用useState挂钩来设置文本长度的值 - 是否需要显示短版本或长版本,最后一个 function 将在文本的短版本和长版本之间切换。

Code example:代码示例:

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;

You're pretty much on the right track.你几乎走在正确的轨道上。 As stated in the react docs here: https://facebook.github.io/react/tips/if-else-in-JSX.html正如这里的反应文档中所述: https : //facebook.github.io/react/tips/if-else-in-JSX.html

it's just using a classic if and a variable, like this:它只是使用经典的if和一个变量,如下所示:

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

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

I know I'm little late to answer this question but instead of using 2 strings why don't you do it by using just 1 string only.我知道我回答这个问题有点晚了,但是为什么不使用 2 个字符串,为什么不只使用 1 个字符串呢?

check out this npm package https://www.npmjs.com/package/react-simple-read-more It'll solve the problem.看看这个 npm 包https://www.npmjs.com/package/react-simple-read-more 就可以解决问题了。

In case you are interested in code: https://github.com/oztek22/react-simple-read-more/blob/master/src/string-parser.jsx如果您对代码感兴趣: https : //github.com/oztek22/react-simple-read-more/blob/master/src/string-parser.jsx

That's the complete solution in React Js:这是 React Js 中的完整解决方案:

Call Component:调用组件:

 <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}/>

Component:成分:

 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM