在工作中经常会遇到这样的需求:如图所示,点击箭头展示剩下内容,为了方便,我封装了一个组件,供大家参考
**注意:
1.fontSize用px表示
2.需要了解下offsetHeight:内容高度+padding高度+边框宽度
3.React的生命周期
**
FoldCom.js
import styles from './FoldCom.css';
import arrow from '../img/arrow.png';
class FoldCom extends React.Component {
constructor(props) {
super(props);
this.state = {
assessInfo: 'auto',
deg: '',
block: '',
overflow: 'auto',
firstSet: true
};
}
componentDidUpdate() {
if (this.state.firstSet) {
if (this.refs.mark.offsetHeight <= this.props.displayHeight) {
this.setState({block: 'none'}); //eslint-disable-line
} else {
this.setState({block: 'block', assessInfo: this.props.displayHeight, overflow: 'hidden'}); //eslint-disable-line
}
this.setState({firstSet: false}); //eslint-disable-line
}
}
render() {
return (
<div>
<pre className={styles.topDes} ref='mark' style={{height: this.state.assessInfo}}>
{
this.props.introduction || ''
}
</pre>
<div className={styles.arrowBox}>
<img
src={arrow}
alt=""
style={{transform: this.state.deg, display: this.state.block}}
onClick={() => {
if (this.state.assessInfo === 'auto') {
this.setState({
assessInfo: this.props.displayHeight,
deg: 'rotate(0deg)'
});
} else {
this.setState({
assessInfo: 'auto',
deg: 'rotate(180deg)'
});
}
}}
/>
</div>
</div>
);
}
}
FoldCom.propTypes = {
displayHeight: React.PropTypes.number.isRequired,
introduction: React.PropTypes.string
};
export default FoldCom;
FoldCom.css
.topDes{
font-size: 17px;
color: #666;
line-height: 28px;
text-align:left;
overflow: hidden;
margin-top: 19px;
transition: all 500ms;
white-space: pre-wrap;
word-break: break-all;
}
.arrowBox{
padding: .5rem 0 .3rem; // 注意这里要用padding
}