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

新手上路,请多包涵

我正在尝试实现一个 Read More 链接,单击后会展开以显示更多文本。我正在尝试以 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 中实现此功能?

原文由 Adi Sivasankaran 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 293
2 个回答

所以基本上你想根据状态属性“扩展”显示一个额外的 div。

您可以有条件地创建组件。如果你不想要一个组件,你可以只返回 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,您将返回 null 作为组件,这基本上意味着什么都没有。所以什么也不会显示。

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

我认为阅读 本文 是一个好的开始。这是一篇非常棒的文章,解释了渲染的基本原理,以及与状态的链接。

你还应该确保你理解这种小例子 http://jsfiddle.net/3d1jzhh2/1/ 看看状态和渲染是如何相互联系的。

原文由 Jeremy D 发布,翻译遵循 CC BY-SA 3.0 许可协议

你可以试试 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}
/>

原文由 Pratik Kumar 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏