gpt4 book ai didi

javascript - 如何使用纯 Reactjs 制作折叠 TextView ?

转载 作者:行者123 更新时间:2023-11-30 15:26:06 25 4
gpt4 key购买 nike

  1. 如果超出 3 行,则 overflow hidden 文本,并在下方显示“显示”/“隐藏”按钮。

  2. 如果文本为3行(3、2、1行),则不显示“显示”/“隐藏”按钮。

有没有办法通过使用纯粹的 Reactjs(不是 jquery)来完成这个?

最佳答案

我没有给你一个完美的解决方案,但这可能对你有帮助。

我在 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>

关于javascript - 如何使用纯 Reactjs 制作折叠 TextView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42943594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com