反应(?)或javascript语法的好奇心

时间:2018-06-18 04:16:59

标签: javascript jquery reactjs syntax jquery-chosen

在通过反应文档(https://reactjs.org/docs/integrating-with-other-libraries.html)进行探索时,我发现了以下代码段:

class Chosen extends React.Component {

   componentDidMount() {
      this.$el = $(this.el);
      this.$el.chosen();
    }

    componentWillUnmount() {
      this.$el.chosen('destroy');
    }

  render() {
    return (
      <div>
        <select className="Chosen-select" ref={el => this.el = el}>
          {this.props.children}
        </select>
      </div>
    );
  }
}

我不承诺的语法如下:

ref = {el => this.el = el} 

该陈述是指什么?我觉得它与:

相同
ref = { el => {
            return this.el = el
            }
       }

但它是什么意思?这段代码中的流程是什么?

1 个答案:

答案 0 :(得分:2)

el => this.el = elfunction(el) { this.el = el }https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)的分类。

ref关键字用于获取元素参考以供将来使用,例如focus事件。我们有两种方法可以使用ref

方式1(使用ref string)

class MyComponent extends Component {
    focusInput() {
        this.refs.inputAge.focus();
    }

    render() {
        return(
            <input ref="inputAge" />
        )
    }
}

通过这种方式,所有参考都进入this.refs

方式2(使用箭头功能)

class MyComponent extends Component {
    focusInput() {
        this.inputAge.focus();
    }

    render() {
        return(
            <input ref={ref => this.inputAge = ref} />
        )
    }
}

通过这种方式,我们可以在任何地方保留参考,因为我们通过功能控制它。