React,ES6-getInitialState在普通的JavaScript类上定义

reactjs React.js

西里神奇

2020-03-12

我具有以下组件(radioOther.jsx):

 'use strict';

 //module.exports = <-- omitted in update

   class RadioOther extends React.Component {

     // omitted in update 
     // getInitialState() {
     //    propTypes: {
     //        name: React.PropTypes.string.isRequired
     //    }
     //    return {
     //       otherChecked: false
     //   }
     // }

     componentDidUpdate(prevProps, prevState) {
         var otherRadBtn = this.refs.otherRadBtn.getDOMNode();

         if (prevState.otherChecked !== otherRadBtn.checked) {
             console.log('Other radio btn clicked.')
             this.setState({
                 otherChecked: otherRadBtn.checked,
             });
         }
     }

     onRadChange(e) {
         var input = e.target;
         this.setState({
             otherChecked: input.checked
         });
     }

     render() {
         return (
             <div>
                 <p className="form-group radio">
                     <label>
                         <input type="radio"
                                ref="otherRadBtn"
                                onChange={this.onRadChange}
                                name={this.props.name}
                                value="other"/>
                         Other
                     </label>
                     {this.state.otherChecked ?
                         (<label className="form-inline">
                             Please Specify:
                             <input
                                 placeholder="Please Specify"
                                 type="text"
                                 name="referrer_other"
                                 />
                         </label>)
                         :
                         ('')
                     }
                 </p>
             </div>
         )
     }
 };

在使用ECMAScript6之前,一切都很好,现在出现1个错误,1个警告,并且我有一个后续问题:

错误:未捕获的TypeError:无法读取null的属性“ otherChecked”

警告: getInitialState是在RadioOther(一个普通的JavaScript类)上定义的。仅使用React.createClass创建的类支持此功能。您是要定义状态属性吗?


  1. 谁能看到错误在哪里,我知道这是由于DOM中的条件语句引起的,但显然我没有正确声明其初始值?

  2. 我应该让getInitialState静态

  3. 如果getInitialState不正确,在什么地方声明我的原型?

更新:

   RadioOther.propTypes = {
       name: React.PropTypes.string,
       other: React.PropTypes.bool,
       options: React.PropTypes.array }

   module.exports = RadioOther;

@ssorallen,此代码:

     constructor(props) {
         this.state = {
             otherChecked: false,
         };
     }

产生"Uncaught ReferenceError: this is not defined",而下面纠正了

     constructor(props) {
     super(props);
         this.state = {
             otherChecked: false,
         };
     }

但是现在,单击另一个按钮现在会产生错误:

Uncaught TypeError: Cannot read property 'props' of undefined

第906篇《React,ES6-getInitialState在普通的JavaScript类上定义》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
猿Green 2020.03.12

添加到罗斯的答案。

您还可以在onChange属性上使用新的ES6箭头功能

它在功能上等效this.onRadChange = this.onRadChange.bind(this);于在构造函数中定义,但在我看来更为简洁。

在您的情况下,单选按钮将如下所示。

<input type="radio"
       ref="otherRadBtn"
       onChange={(e)=> this.onRadChange(e)}
       name={this.props.name}
       value="other"/>

更新资料

这种“更简洁”的方法比@Ross Allen的答案中提到的选项效率低,因为每次render()调用方法时都会生成一个新函数。

TonyEvaL 2020.03.12

如果您正在使用babel-plugin-transform-class-propertiesbabel-preset-stage-2(或stage-1或stage-0),则可以使用以下语法:

class RadioOther extends React.Component {

  static propTypes = {
    name: React.PropTypes.string,
    ...
  };

  state = {
      otherChecked: false,
  };

  onRadChange = () => {
    ...
  };

  ...

}
村村老丝 2020.03.12
  • getInitialState在ES6类中不使用。而是this.state在构造函数中分配
  • propTypes 应该是静态类变量或分配给该类,而不应该分配给组件实例。
  • 成员方法在ES6类中不是“自动绑定”的对于用作回调的方法,请使用类属性初始化程序或在构造函数中分配绑定的实例。
export default class RadioOther extends React.Component {

  static propTypes = {
    name: React.PropTypes.string.isRequired,
  };

  constructor(props) {
    super(props);
    this.state = {
      otherChecked: false,
    };
  }

  // Class property initializer. `this` will be the instance when
  // the function is called.
  onRadChange = () => {
    ...
  };

  ...

}

在React的文档中了解有关ES6类的更多信息:将函数转换为类

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android