Where is my *ref*

#1

今天楼主遇到一种情况无论如何也无法通 this.refs.myComponent 拿到想要的元素. render 代码如下(使用了 react-bootstrap)

render : function(){
      retrun (
	<Modal.Dialog>
	      <Modal.Header>
	         <Modal.Title>Modal title</Modal.Title>
	      </Modal.Header>
	
	      <Modal.Body>
	         <MyComponent ref="myComponent" />
	      </Modal.Body>
	</Modal.Dialog>
     )
}

调试了半天才发现因为嵌套在其他 component 中这个 ref 已经不属于我这render 函数所在的 component 了. 所以我使用了另一种设置 component ref 的方法,叫做: The ref Callback Attribute

修改后的 render 方法. 然后就可以通过 this.myComponent 拿到相对应的 component 了

render : function(){
      var that = this;
      retrun (
	<Modal.Dialog>
	      <Modal.Header>
	         <Modal.Title>Modal title</Modal.Title>
	      </Modal.Header>
	
	      <Modal.Body>
	         <MyComponent ref={function(comp){ that.myComponent = comp; } }  />
	      </Modal.Body>
	</Modal.Dialog>
     )
}
1 Like
#2

哈哈是的,顺便问下我今天遇到的问题, 项目是react + reflux + webpack + babel.js 解析器解析的.

'use strict';

export default function hostnameFromUrl(str: string): string {
    let url = document.createElement('a');
    url.href = /^(f|ht)tps?:\/\//i.test(url) ? 'http://' + str : str;
    return url.hostname;
}

这段 es6 该如何理解,没有见到过呢.