reactjs - React中div/paragraph标签中的最大字符数

标签 reactjs

在我的段落达到 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/

相关文章:

reactjs - 如何加载图像 react babel

javascript - 为什么jqgrid上的文本框不响应鼠标点击?

javascript - 如何在 react js中使用json在表中显示数据?

javascript - 如何以动态形式创建和存储多个输入的值?

twitter-bootstrap - 如何插入 bootstrap.js 来 react 应用程序?

mongodb - 在 Falcor 中如何使用数据库?

java - 如何在 Spark Java 响应中包含模型数据以供 React JS 访问?

javascript - 获取id值并将其设置为react中的状态

javascript - 在 ref 内渲染 ReactPortal

jquery - React 和 jQuery 事件处理程序以错误的顺序触发