代码之家  ›  专栏  ›  技术社区  ›  Jay Jeong

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

  •  0
  • Jay Jeong  · 技术社区  · 8 年前

    同时浏览react文档( 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 回复  |  直到 8 年前
        1
  •  2
  •   Kishan Mundha    8 年前

    el => this.el = el 很抱歉 function(el) { this.el = el } ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions )

    ref 关键字,用于获取元素引用以供将来使用,如 focus 事件。我们有两种方法 裁判 .

    方式1(使用ref字符串)

    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} />
            )
        }
    }
    

    通过这种方式,我们可以保持ref在任何我们想要的地方,因为我们通过函数控制它。