我正在尝试实现一个Read More链接,该链接会在单击后扩展为显示更多文本。我正在尝试以React方式做到这一点。
Read More
<!--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的新手。我不确定如何处理render方法中的所有内容。如何在纯React中实现此功能?
因此,基本上,您想根据状态属性“ expanded”显示一个额外的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()使用新状态触发。
setState()
render()
如果expanded为false,那么您将返回null作为组件,这基本上意味着什么。所以什么也不会显示。
当您单击链接时,它将更新您的状态和扩展值,因此您将返回一个div作为组件并显示出来。
我认为读这本书是一个好的开始。这是一篇非常出色的文章,并说明了渲染的基本工作原理以及与状态的链接。
您还应该确保您了解此类小示例http://jsfiddle.net/3d1jzhh2/1/,以了解状态和渲染如何相互链接。