如果超过3行,则隐藏溢出文字,并显示"显示" /"隐藏"按钮如下。
如果文字分为3行(3,2,1行),则不显示"显示" /"隐藏"按钮。
有没有办法通过使用纯粹的Reactjs(而不是jquery)来实现这一目标?
答案 0 :(得分:0)
我没有给你一个完美的解决方案,但这可能对你有帮助。
我在react中创建了一个 Test 组件,它将文本段落作为子元素接收。 如果段落长度大于3,那么您将看到显示隐藏按钮,否则它将按原样显示。
如何获得行数? 我已经将行高设置为1 em,高度设置为3.3 em,所以现在div只允许三行。
class Test extends React.Component {
constructor(){
super();
this.state = {
height:'3.3em'
};
}
countLines = () => {
let height = this.testComp.offsetHeight;
if ( (height - 2 ) / 16 > 3.3 ) {
this.setState({showButton:true});
}
}
showHidePara=() => {
if (this.state.height == 'auto') {
this.setState({height:'3.3em'});
} else {
this.setState({height:'auto'});
}
}
componentDidMount() {
this.countLines();
}
render() {
return (
< div>
{ this.state.showButton ?
<button onClick={this.showHidePara}> Show/hide </button>
: null
}
<div id ="parent" style={{height:this.state.height}}>
<div id = "content" ref={(c) => this.testComp = c } style={{height:'auto'}}>
{this.props.children}
</div>
</div>
</div>
);
}
}
const Comp = () => (
<div>
<h3> Test 1 </h3>
<hr/>
<Test>
This is a test line.This is a large test line.This is a large test line.This is a large test line.This is a test line.This is a large test line.This is a large test line.This is a test line.This is a large test line.This is a large test line..This is a test line.This is a large test line.This is a large test line.This is a test line.This is a large test line.This is a large test line.
</Test>
<hr/>
<h3> Test 2 </h3>
<hr/>
<Test> This is a test line.This is a large test line.
</Test>
</div>
);
ReactDOM.render( <Comp /> ,
document.getElementById('root')
);
#content {
width:auto;
line-height: 1.1em;
}
#parent {
border : 1px solid red;
overflow : hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>