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

时间:2016-01-05 16:21:59

标签: javascript reactjs

我有一个相对简单的代码片段,它是用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是在TextArea上定义的,TextArea是一个普通的JavaScript类。这仅适用于使用React.createClass创建的类。你的意思是改为定义一个州属性吗?

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

2 个答案:

答案 0 :(得分:3)

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

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

Example

答案 1 :(得分:1)

对于州,您只需在this.state = {}内添加constructor即可。一个例子可能是:

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

对于默认道具,您可以使用TextArea.defaultProps。一个例子可能是:

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

这不在您的课堂之外,就像您进行验证检查一样。

相关问题