在 TextArea 问题中反应计数单词

React Counting Words in a TextArea PROBLEM

这是编辑后的代码。

    <textarea
      className= "textarea"
      placeholder="write the description here"
      value={this.state.input} 
      onChange={(ev) => {
        this.updateBody(ev.target.value)
        }
      }>
    </textarea>

然后调用函数将数据保存到 Firebase。

 updateBody = async (val) => {
    await this.setState({ input: val });
    await this.setState({ wordsCounted :val.split(' ').length });
    await this.setState({charactersCounted : val.length })
    /*assign the number of words inside the textarea to the variable wordsCounted*/
    this.update();
  };
  updateTitle = async (txt) => {
    await this.setState({ title: txt });
    this.update();
  }
  update = debounce(() => {
    this.props.noteUpdate(this.state.id, {
      title: this.state.title,
      body: this.state.input,
      /*Send the value of the var wordsCounted to Firebase*/
      wordsCounted : this.state.wordsCounted,
      charactersCounted : this.state.charactersCounted

    })
  }, 750);

问题是我不知道为什么 titlebody 被保存而 wordsCountedcharactersCounted 没有被保存。

检查错别字。

this.state.input.length不是this.state.input.lenght

它不会计算字数。它会计算字符数。

因此,您必须使用 this.state.input.split(' ').length 来计算字数。

如果仍然有错误,则将组件添加到问题中。

解决方案在 onChange 事件的事件对象中。如果在 onChange 事件中为文本区域中的文本长度设置状态,则可以获得字符数。如果您使用 Zunayed Shahriar 的建议来计算单词数,那么状态将存储单词数。但是,这里有一个错误需要修复:space 字符被算作一个单词。因此,当“你好”是一个词时,“你好”是两个词。 “hello world”也算两个字

这是我建议的代码。请注意,我使用值状态使 textarea 成为受控输入。

import React from "react";

class App extends React.Component {
  state = { value: '', length: 0 }

  render() {
    console.log(this.state.length)

    return (
      <div>
        <h1>Hello</h1>
        <textarea value={this.state.value} onChange={(e) => {
          this.setState({ value: e.target.value })
          this.setState({ length: e.target.value.split(' ').length })
        }}></textarea>
      </div>
    )
  }
}

export default App

作为已接受答案的参考,使用

this.setState({ length: e.target.value.trim().split(' ').length })

获得正确的字数,因为末尾的空格算作一个字。