在典型的React数据流中, props
是父组件和子组件交互的惟一方式,要修改一个子组件,你须要使用新的props来从新渲染它。可是在某些状况下,你须要在典型的数据流以外强制修改子组件、或获取组件的属性值。被修改的子组件多是一个React组件的实例,也多是一个DOM元素。html
Refs
提供了一种容许咱们访问DOM
节点或在render方法中建立的React元素的方式。数组
经过React.crateRef()建立
Refs
可使用React.createRef()
建立,并经过ref
属性附加到React元素。在构造组件时,一般将Refs
分配给实例属性,以即可以在整个组件中调用. ref
做为原生DOM
的属性传入bash
class Index extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
this.getInput = this.getInput.bind(this);
}
componentDidMount() {
console.log(this.componentRef.current)
}
getInput() {
console.log(this.inputRef.current.value)
}
render() {
return (
<div>
<input ref={this.inputRef}/>
<button onClick={this.getInput}>getValue</button>
</div>
)
}
}
复制代码
不过此例子并不恰当,在实际运用中能经过状态申明的方式解决,就避免使用ref
。 ref
做为组件的属性传入函数
class IndexPage extends React.PureComponent{
constructor(props) {
super(props);
this.componentRef = React.createRef()
}
componentDidMount() {
console.log(this.componentRef.current)
}
render() {
return (
<div>
<Ref ref={this.componentRef} />
</div>
);
}
}
复制代码
当ref
传递给render中的元素时,对该节点的引用能够经过生成的Refs
对象的current属性访问。但current属性的值因节点的类型不一样而有所不一样。ui
ref
做用于html元素时,构造函数中使用React.createRef()
建立的ref
接收底层DOM
元素做为其current属性的值。ref
做用于class申明的React
组件时,构造函数中使用React.createRef()
建立的ref
接收组件实例做为其current属性的值。DOM
元素或组件的实例传递给current属性,在组件卸载时给current属性值传入 null
,ref
会在 componentDidMount
或 componentDidUpdate
生命周期钩子函数触发前更新。refs
能够经过回调函数的形式建立,它能助你更精细地控制什么时候refs被设置和解除。 回调函数接收DOM
元素或React组件实例做为参数,并将该参数添加到实例属性上,以使它们能在其余地方被存储和访问。回调函数形式建立的ref
,经过回调函数的参数直接引用不须要经过current。 ref
做为原生DOM
的属性传入this
class Index extends React.Component {
constructor(props) {
super(props);
this.setInputRef = el => {
this.inputRef = el
};
this.getInput = this.getInput.bind(this);
}
getInput() {
console.log(this.inputRef)
}
render() {
return (
<div>
<input ref={this.setInputRef} />
<button onClick={this.getInput}>getValue</button>
</div>
)
}
}
复制代码
ref
做为组件的属性传入spa
class IndexPage extends React.PureComponent{
constructor(props) {
super(props);
}
componentDidMount() {
console.log(this.componentRef)
}
render() {
return (
<div>
<CallBackRef ref={ el => {this.componentRef = el}} />
</div>
);
}
}
复制代码
当ref
做为原生DOM
的属性传入时回调函数的参数便是该DOM
对象,ref
做为组件的属性传入时,回调函数的参数便是该React组件的实例对象。React将在组件挂载时,会调用ref
回调函数并传入对象参数。在 componentDidMount 或 componentDidUpdate 触发前,React 会保证 refs 必定是最新的。code
当组件插入到 DOM 后,ref
属性添加一个组件的引用于到 this.refs
,经过this.refs.xxx
获取对节点的引用component
class Index extends React.Component {
constructor(props) {
super(props);
this.getInput = this.getInput.bind(this);
}
getInput() {
console.log(this.refs.inputRef)
}
render() {
return (
<div>
<input ref="inputRef" />
<button onClick={this.getInput}>getValue</button>
</div>
)
}
}
复制代码
在React16.3以后的版本中该方法已经弃用,建议使用前两种。cdn