我正在尝试实现一个 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 许可协议
所以基本上你想根据状态属性“扩展”显示一个额外的 div。
您可以有条件地创建组件。如果你不想要一个组件,你可以只返回 null。我只会有一个像这样的小方法:
你的渲染函数应该变成:
每次调用
setState()
都会触发render()
使用新状态。如果 expanded 为 false,您将返回 null 作为组件,这基本上意味着什么都没有。所以什么也不会显示。
当您单击您的链接时,它会更新您的状态和扩展值,因此您将返回一个 div 作为组件并显示出来。
我认为阅读 本文 是一个好的开始。这是一篇非常棒的文章,解释了渲染的基本原理,以及与状态的链接。
你还应该确保你理解这种小例子 http://jsfiddle.net/3d1jzhh2/1/ 看看状态和渲染是如何相互联系的。