React, ES6 - getInitialState was defined on a plain JavaScript class

前端 未结 3 1229
野趣味
野趣味 2020-12-22 21:51

I have the following component (radioOther.jsx):

 \'use strict\';

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

   class RadioOther extends Rea         


        
相关标签:
3条回答
  • 2020-12-22 21:57

    Adding to Ross's answer.

    You could also use the new ES6 arrow function on the onChange property

    It is functionally equivalent to defining this.onRadChange = this.onRadChange.bind(this); in the constructor but is more concise in my opinion.

    In your case the radio button will look like the below.

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

    Update

    This "more concise" method is less efficient than the options mentioned in @Ross Allen's answer because it generates a new function each time the render() method is called

    0 讨论(0)
  • 2020-12-22 22:02
    • getInitialState is not used in ES6 classes. Instead assign this.state in the constructor.
    • propTypes should be a static class variable or assigned to the class, it should not be assigned to component instances.
    • Member methods are not "auto-bound" in ES6 classes. For methods used as callbacks, either use class property initializers or assign bound instances in the constructor.
    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 = () => {
        ...
      };
    
      ...
    
    }
    

    See more in the React's documentation about ES6 Classes: Converting a Function to a Class

    0 讨论(0)
  • 2020-12-22 22:20

    If you are using babel-plugin-transform-class-properties or babel-preset-stage-2 (or stage-1, or stage-0), you can use this syntax:

    class RadioOther extends React.Component {
    
      static propTypes = {
        name: React.PropTypes.string,
        ...
      };
    
      state = {
          otherChecked: false,
      };
    
      onRadChange = () => {
        ...
      };
    
      ...
    
    }
    
    0 讨论(0)
提交回复
热议问题