jac*_*pal 2 css ecmascript-6 reactjs
我正在尝试在 css3、ES6 和 React 中完成阅读更多功能。
我有一个很长的描述(这来自服务器,所以它是动态的),我想在其中添加“阅读更多”功能。如果描述超过 3 行,那么按钮/链接应该可以作为“阅读更多”,当我单击该按钮时,应该显示其余的描述。
这是我的代码:
反应:
<div className="content">
Description of the product
<button onClick=(() => {})>Read more</button>
</div>
Run Code Online (Sandbox Code Playgroud)
CSS:
.content{
overflow: hidden;
line-height: 1.2em;
height: 3.6em;
}
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚的是,当我单击“阅读更多”按钮时,如何更改 div id 以使其高度为自动。我有 javascript 代码,但我想在 ES6 中实现它
JS:
document.querySelector('button').addEventListener('click', function()
{
document.querySelector('#content').style.height= 'auto';
this.style.display= 'none';
});
Run Code Online (Sandbox Code Playgroud)
任何帮助表示高度赞赏!
我在这里为您创建了一个小提琴:https : //jsfiddle.net/jwm6k66c/3063/。你想避免在使用 React 时直接操作 dom。首选方法是使用组件state来切换contentdiv上的类。
class App extends React.Component {
constructor(){
this.description = getDescription();
this.state = {
expanded: false
}
}
render(){
const { expanded } = this.state;
const toggledClass = expanded ? 'expanded' : 'collapsed';
return(
<div>
<div className={`content ${toggledClass}`}>
{this.description}
</div>
<button onClick={() => this.setState({ expanded: !expanded })}>
{expanded ? 'View Less' : 'View More'}
</button>
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
CSS
.content {
overflow: hidden;
line-height: 1.2em;
height: 3.6em;
}
.content.collapsed{
overflow: hidden;
}
.content.expanded{
overflow: visible;
height: auto;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2950 次 |
| 最近记录: |