【问题标题】:Convert Back to ES6 Classes in JavaScript在 JavaScript 中转换回 ES6 类
【发布时间】:2018-03-06 23:21:13
【问题描述】:

我正在努力将以下代码更改为等效的 ES6 语法的等效语法。

export default class EventSessionItem extends Component {
    state = {
        isDetailsVisible: false,
    };

    revealDetails = () => {
        this.setState({isDetailsVisible: true});
    };

我原以为下面会是转换,但显然不是。一切都以红色点亮,表示语法错误。

export default class EventSessionItem extends Component {

  constructor() {
    isDetailsVisible = false;
  }

  function revealDetails  {
    this.setState({isDetailsVisible: true});
  };

【问题讨论】:

    标签: javascript ecmascript-6 ecmascript-next


    【解决方案1】:

    带有类初始化器的代码对构造函数中的属性分配进行了取消:

    export default class EventSessionItem extends Component {
      constructor(...args) {
    //^^^^^^^^^^^
        super(...args);
    
        this.state = {
    //  ^^^^^
            isDetailsVisible: false,
        };
    
        this.revealDetails = () => {
    //  ^^^^^
            this.setState({isDetailsVisible: true});
        };
      }
    }
    

    【讨论】:

      【解决方案2】:

      我想这就是你想要的。假设你正在使用 React。

      export default class EventSessionItem extends Component {
      
        constructor(props) {
          super(props);
      
          this.state = {
            isDetailsVisible: false
          }
      
          this.revealDetails = this.revealDetails.bind(this);
        }
      
        revealDetails() {
          this.setState({isDetailsVisible: true});
        }
      }
      

      您在第一个示例中使用的两个类字段state =revealDetails = () => 还不是标准的一部分。 https://github.com/tc39/proposal-class-fields

      【讨论】:

      • 你还需要一个 this.revealDetails = this.revealDetails.bind(this) 在构造函数中
      【解决方案3】:

      采用您的一些修复方法:

      class Component {}
      class EventSessionItem extends Component {
      
        constructor() {
          super();
          this.isDetailsVisible = false;
        }
      
        setState(newState) {
          this.isDetailsVisible = newState;
        }
        
        // This is to illustrate!
        getState() {
          return this.isDetailsVisible;
        }
      
        revealDetails() {
          this.setState({
            isDetailsVisible: true
          });
        };
      }
      
      var esi = new EventSessionItem();
      esi.revealDetails();
      console.log(esi.getState());
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

      • 我认为他正在使用 React,即使他没有标记它。
      猜你喜欢
      • 1970-01-01
      • 2019-12-11
      • 1970-01-01
      • 2017-09-30
      • 2020-05-27
      • 2016-07-29
      • 2018-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多