在我的段落达到 250 个字符后,我需要添加一个“阅读更多”链接。使用 JavaScript 得到了许多解决方案,但我无法使用 ReactJS 来做到这一点。任何形式的帮助都会很棒! 谢谢 例子 : 文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字文字...阅读更多
最佳答案
如果我理解正确的话,与您在网上看到的不同之处在于,如果文本少于 250 个字符,您不希望显示阅读更多
按钮。
如果您可以分享您已有的内容,那就太好了,但为了以防万一,这里有一个原型(prototype):
class LongText extends Component {
state = { showAll: false }
showMore = () => this.setState({showAll: true});
showLess = () => this.setState({showAll: false});
render() {
const {content, limit} = this.props;
const {showAll} = this.state;
if(content.length<=limit) {
// there is nothing more to show
return <div>{content}<div>
}
if(showAll) {
// We show the extended text and a link to reduce it
return <div>
{content}
<a onClick={this.showLess}>Read less</a>
</div>
}
// In the final case, we show a text with ellipsis and a `Read more` button
const toShow = content.substring(0,limit)+"...";
return <div>
{toShow}
<span onClick={this.showMore}>Read more</a>
</div>
}
}
编辑:带钩子(Hook)
const {useState} = React;
const LongText = ({ content,limit}) => {
const [showAll, setShowAll] = useState(false);
const showMore = () => setShowAll(true);
const showLess = () => setShowAll(false);
if (content.length <= limit) {
// there is nothing more to show
return <div>{content}</div>
}
if (showAll) {
// We show the extended text and a link to reduce it
return <div>
{content}
<button onClick={showLess}>Read less</button>
</div>
}
// In the final case, we show a text with ellipsis and a `Read more` button
const toShow = content.substring(0, limit) + "...";
return <div>
{toShow}
<button onClick={showMore}>Read more</button>
</div>
}
const App = () => <div>
<LongText content = "Short text" limit = {10}/>
<LongText content = "Very long text, very very long" limit = {10} />
</div>
ReactDOM.render( <App/>,document.getElementById('react'));
button {
margin-left: 4px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
关于reactjs - React中div/paragraph标签中的最大字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40255345/