Ref 拥有以下特色:
通常来说,只在不牵涉画面显示,
如管理 focus、选择文字或影音播放时
才会使用到 Ref。
Ref 属於命令式(Imperative)编程,官方建议不要在可以宣告性(Declarative)完成事情的地方使用 Ref。
呼叫 createRef
可以建立新的 Ref
const ref = React.createRef();
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
Ref 藉由 ref
参数依附在 React element 上
当 component 建立後,
将 Ref 赋值到某个 instance 的属性上,
之後便能在整个 component 内被参考到。
const node = this.myRef.current;
藉由 current
属性
可以取得指向该 DOM 节点的参考
Ref 的值会根据节点的类型而有所不同:
ref
参数时,使用 React.createRef()
建立 ref
会取得它底下的 DOM element 来做为它的 current
属性。ref
参数时,ref
取得被 mount 的 component 上的 instance 来当作他的 current
。function component 没有 instance,因此无法使用
ref
。
写法一
myRef = React.creatRef();
console.log(this.myRef);
console.log(this.myRef.current);
console.log(this.myRef.current.innerHTML);
render(){
return <div ref ={this.myRef}>内容</div>
}
写法二
myRef = null;
console.log(this.myRef);
console.log(this.myRef);
console.log(this.myRef.innerHTML);
render(){
return <div ref ={node => this.myRef = node }>内容</div>
}
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// 产生一个可以储存 textInput DOM element 的 ref
this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// 特别利用原生的 DOM API 来关注文字的输入
// 注意:我们正利用「current」来取得 DOM 节点
this.textInput.current.focus();
}
render() {
// 告诉 React 我们想要将 <input> ref
// 和我们在 constructor 产生的 `textInput` 连结
return (
<div>
<input
type="text"
ref={this.textInput} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}
React 会在 component mount 的时候
将 DOM element 赋值到 current 属性,
并在 unmount 时将它清空回 null。
Ref 的更新发生在生命周期
componentDidMount 或
componentDidUpdate 之前。
class AutoFocusTextInput extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
componentDidMount() {
this.textInput.current.focusTextInput();
}
render() {
return (
<CustomTextInput ref={this.textInput} />
);
}
}
class CustomTextInput extends React.Component {
// ...
}
<<: Day24 - 如何盘中计算技术指标且发送讯号到line: 不同频率分K计算
>>: 【把玩Azure DevOps】Day27 Build Pipeline的YAML结构描述:多个Agent Job
本系列文之後也会置於个人网站 +-------------------+ | Authz Serv...
Objective-C class 定义一个物件(object),该物件含有资料和一些行为。有时可能...
安装方式 根据官网介绍,本次铁人赛会着重介绍下列三种安装方式: CDN连结 快速建立react环境的...
VECTOR TABLE 当Exception发生并由 Cortex-M3 处理时,处理器将需要定位...
在操作元件那天,已经大略谈到在Activity 上架上元件就像在写Windows Form 上的元件...