反应没有箭头的JavaScript箭头功能?

时间:2019-02-01 10:30:54

标签: javascript reactjs arrow-functions slate

我不知道该如何在javascript中工作

renderMarkButton(type, icon) {

它看起来像一个箭头函数,但是没有箭头。这是上下文:

class HoverMenu extends React.Component {

  renderMarkButton(type, icon) {
    const { editor } = this.props
    return (
      <div className="editorButton" 
            onMouseDown={event => this.onClickMark(event, type)}>
        <FontAwesomeIcon color="#666" active={isActive} 
            className="editorButton" icon={icon}  />
        </div>
    )
  }
  render() {
    return (
      <div>
        {this.renderMarkButton('bold', {...faBold})}
      </div>
    )
  }
}

我也对

感到困惑
  const { editor } = this.props
我相信

来自Slate。在这种情况下,我希望this.props为{type,icon}。

3 个答案:

答案 0 :(得分:8)

关于您的问题:

  1. renderMarkButton(type, icon) {只是es6类语法: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
  2. const { editor } = this.props被称为“解构”。您可以在这里阅读有关内容:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

希望有帮助:)

答案 1 :(得分:1)

箭头和绑定方法对于将它们作为回调传递以供稍后调用非常有用:

<Component onClick={this.clickHandler}/>

renderMarkButton并非如此,因为它是在与正确的this上下文一起使用的地方调用的:

this.renderMarkButton('bold', {...faBold})

renderMarkButton是类原型方法。它不像箭头功能那样工作,因为它没有绑定到上下文。在错误的上下文中调用它会导致错误,因为将没有this.props对象:

const unboundFunction = this.renderMarkButton;
unboundFunction('bold', {...faBold});

答案 2 :(得分:0)

根据新的class关键字,这是一种特殊的语法,可让您创建类。

基本上,这些是该特定类的方法,您无法使用该特定语法在该类之外定义任何其他方法。

有关更多信息,请consider MDN as your best partner

相关问题