react中div / paragraph标记中的最大字符数

时间:2016-10-26 06:40:07

标签: reactjs

我需要添加一个"阅读更多"链接后我的段落达到250个字符..使用javascript的许多解决方案,但我无法用reactjs做到这一点。任何形式的帮助都会很棒! 谢谢 示例: 文本文本文本texttext texttext texttext texttext texttext texttext texttext text ...阅读更多

3 个答案:

答案 0 :(得分:4)

如果我理解正确,与您在网上看到的不同之处在于,如果文字少于250个字符,则您不想显示Read more按钮。

如果你能分享你已有的东西会很棒,但为了以防万一,这里有一个原型:

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>
    }
}

答案 1 :(得分:2)

您仍然可以使用Implementing a Read More link in React.js中的答案,并使用substr()方法加载简化文字,如下所示:

var component = React.createClass({
    getInitialState: function() {
       return {
          expanded: false,
          myText: 'bla bla bla'
       };
    },

    expandedText: function() {
        this.setState({
          expanded: true
        });       
    },

    getMoreTextDiv = function() {
        if (this.state.expanded) {
          return myText;
        } else {
          return myText.substr(0, 250);
        }
    }

    render: function() {
        var expandedDiv = this.getMoreTextDiv();
        return (
           <div>
               <a onClick={ this.expandedText }>Read more</a>
               { expandedDiv }
           </div>
        );
    }
});

答案 2 :(得分:2)

比使用ES6发布的其他人更简单,更具表现力的例子:

    Intent DataSyncing = new Intent(getBaseContext(), DataSyncingScheduledReceiver.class);
    DataSyncing.setAction(DataSyncingScheduledReceiver.ACTION_DATASYNC_RECEIVER);
    PendingIntent DataSyncingIntent = PendingIntent.getBroadcast(getBaseContext(),1003, DataSyncing, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager alarmManagerdatasync = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManagerdatasync.cancel(DataSyncingIntent);
    DataSyncingIntent.cancel();

Here's a fiddle证明了这一点。