React Modifying Textarea Values

前端 未结 2 706
攒了一身酷
攒了一身酷 2021-02-02 05:30

I am working on a project which is basically notepad. I am having problems though updating the

The value of the following uncontrolled textarea can be changed because of use of defaultValue or no value attribute




The value of the following controlled textarea can be changed because of how value is mapped to a state as well as the onChange event listener


Here is my solution using different syntax. I prefer the auto-bind than manual binding however, if I were to not use {(event) => this.onXXXX(event)} then that would cause the content of textarea to be not editable OR the event.preventDefault() does not work as expected. Still a lot to learn I suppose.

class Editor extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      textareaValue: ''
    }
  }
  handleOnChange(event) {
    this.setState({
      textareaValue: event.target.value
    })
  }
  handleOnSubmit(event) {
    event.preventDefault();
    this.setState({
      textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
    })
  }
  render() {
    return 
this.handleOnSubmit(event)}>
} } ReactDOM.render(, document.getElementById("content"));

The versions of libraries are

"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4" 

提交回复
热议问题