我什么时候应该在React组件中使用getInitialState

时间:2015-03-17 02:13:31

标签: reactjs

我有一个React组件,可以在单击组件时切换className

var Foo = React.createClass({
  getInitialState: function() {
    return {className: ''}
  },

  render: function(){
    var className = 'bar ' + this.state.className
    return React.createElement('div', {className: className, onClick: this.onClick})
  },

  onClick: function() {
    this.setState({className: 'baz'})
  }
});

它工作正常,但是当我渲染应用服务器端时,我收到以下错误

Warning: getInitialState was defined on a component, a plain JavaScript class.
This is only supported for classes created using React.createClass.
Did you mean to define a state property instead?

我的构建步骤是这样设置的

var Foo = require('./Foo');
var factory = React.createFactory(Foo);
module.exports = React.renderToString(factory({}));

为什么我做错了,应该怎么做?

1 个答案:

答案 0 :(得分:2)

我不确定这是否有帮助,但在使用fluxible时,这是我使用JSX作为require组件的一部分的语法

var app = new Fluxible({
  component: React.createFactory(require('./Components/startup.react.jsx'))
});