React TextArea组件-如何在ES6中使用getInitalState()

React TextArea Component - How to use getInititalState() in ES6?

本文关键字:getInitalState ES6 组件 TextArea React      更新时间:2023-09-26

我有一个相对简单的片段,它是用JSX/ES6编写的。

import React from 'react'
class TextArea extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <textarea defaultValue={this.props.text}></textarea>
        <h3>{this.props.text.length}</h3>
      </div>
    )
  }
}
TextArea.propTypes = {
  text: React.PropTypes.string
}

export default TextArea;

由于该类不是用React.createClass生成的,因此尝试添加getInitialState会导致控制台出现红色大警告:

警告:getInitialState是在纯JavaScript类TextArea上定义的。这只支持使用React.createClass创建的类。你是想定义一个状态属性吗?

如何在ES6类中正确使用getInitialState()

类内构造函数需要设置state属性

constructor(props) {
  super(props);
  this.state = {  }
}

Example

对于state,您只需在constructor中添加this.state = {}。例如:

constructor (props) {
    super(props);
    this.state = {
        placeHolder: 'Type your stuff here!'
        };
    }

对于默认道具,您将使用TextArea.defaultProps。例如:

TextArea.defaultProps = {
    placeHolder: this.state.placeHolder
};

这超出了您的类,就像您进行验证检查一样。