Adi*_*ran 5 html javascript css dom reactjs
我正在尝试实现一个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>
Run Code Online (Sandbox Code Playgroud)
/* JavaScript */
/* @jsx DOM */
var component = React.createClass({
getInitialState: function() {
return {
expanded: false
};
},
expandedText: function() {
this.setState({
expanded: true
});
},
render: function() {
return (
<div>
</div>
);
}
});
Run Code Online (Sandbox Code Playgroud)
我是 React 的新手。我不确定如何处理渲染方法中的所有内容。如何在纯 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;
}
}
});
Run Code Online (Sandbox Code Playgroud)
你的渲染功能应该变成:
render: function() {
var expandedDiv = this.getMoreTextDiv();
return (
<div>
<a onClick={this.expandedText}>Read more</a>
{ expandedDiv }
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
每次调用时setState()
都会render()
使用新状态触发。
如果expanded 为false,您将返回null 作为组件,这意味着基本上什么都没有。所以什么都不会显示。
当您单击链接时,它会更新您的状态和扩展值,因此您将返回一个 div 作为组件并显示出来。
我认为阅读这篇文章是一个好的开始。这是一篇非常棒的文章,解释了渲染的基本工作原理,以及与状态的链接。
您还应该确保您了解这种小示例http://jsfiddle.net/3d1jzhh2/1/以了解状态和渲染是如何相互关联的。
归档时间: |
|
查看次数: |
23151 次 |
最近记录: |