从ReactJs中的TextArea计算字符

时间:2016-01-19 10:07:27

标签: javascript reactjs

我有一些我想在反应中实现的东西,它是一个简单的功能,可以计算输入到textarea的字符数。

这里是源代码

var WordCount = React.createClass({

getInitialState: function() {
    return{ contacts: [], fullName: "What Ever", smsBalance: 0, command: 'Send Now', charsPerPage: 160, pageCount:0 };
},

wordCount: function(e){

    var currentText = e.target.value;
    //Now we need to recalculate the number of characters that have been typed in so far
    var characterCount = currentText.length;
    var charsPerPageCount = this.state.charsPerPage;
    var unitCount = Math.round(characterCount/charsPerPageCount);
    this.setState({pageCount: unitCount});
},

render: function() {
    return(
        <div className="md-card">


        <div className="user_content">
            <ul className="uk-margin">
                <div className="uk-margin-top">

                    <div className="uk-grid" data-uk-grid-margin="">
                        <div className="uk-width-medium-1-1">
                            <div className="md-input-wrapper">
                            <label htmlFor="Message">And Now Your Message</label>
                            <textarea className="md-input autosize_init" cols="30"
                                      data-val="true"
                                      data-val-required="The Message field is required."
                                      id="Message" ref="Message"
                                      rows="3" onChange={this.wordcount} style={{overflowX: "hidden", wordWrap: "break-word", height: 97+"PX"}}></textarea>
                            <span className="md-input-bar"></span></div>
                            <br/>
                            <span className="md-color-grey-300">
                                Current cost {this.state.pageCount}
                            </span>
                        </div>
                    </div>



                </div>
            </ul>
        </div>
        </div>
    );
}
});

ReactDOM.render(<WordCount/>, document.getElementById("PageContent"))

理想情况下,我打算实现的是计算用户在文本区域中输入的字符数,并将该数字除以某个预设值以获取页数并显示用户输入的页数给用户

但是,sate变量'pageCount'永远保持为零。请问我做错了什么

此致 彼得

1 个答案:

答案 0 :(得分:4)

一个愚蠢的错误,将onChange = {this.wordcount}更改为onChange = {this.wordCount}。