React三大核心属性—refs
1. refs基本认识
Refs其实是提供了一个对真实DOM(组件)的引用,我们可以通过这个引用直接去操作DOM(组件)
2. 为什么要用refs
我们在使用React写代码的时候对Refs的使用比较少,因为我们很少直接操作底层DOM元素,而是通过在render里编写我们的页面结构,再由React来组织DOM元素的更新。
而在少数情况中,有些需求要求我们对页面的真实DOM进行直接操作,这就要求我们有直接访问真实DOM的能力,而Refs就为我们提供了这种能力。
3. 创建ref的三种形式
字符串形式的ref
在官网文档中也标记了过时的API。它已过时并可能会在未来的版本被移除。在render
方法中使用字符串定义一个ref
:
<script type="text/babel">
// 定义函数组件
class Demo extends React.Component {
showData1 = () => {
console.log(this.refs.input1.value);
}
render() {
return (
<div>
{/*字符串形式的ref*/}
<input ref="input1" type="text" placeholder="点击按钮提示数据" />
<button onClick={this.showData1}>点我提示左侧数据</button>
</div>
)
}
}
// 渲染组件到页面
ReactDOM.render(<Demo />, document.querySelector('#test'))
</script>
回调函数方式的ref
React 也支持另一种设置 refs 的方式,也就是回调形式的refs。它能使我们更加容易并且精细的控制refs的设置和解除。
在ref中,你会传递一个函数。这个函数中接受 React 组件实例或 HTML DOM 元素作为参数,以使它们能在其他地方被存储和访问。
<script type="text/babel">
// 定义函数组件
class Demo extends React.Component {
showData2 = () => {
console.log(this.input2.value);
}
render() {
return (
<div>
{/* 回调形式的ref c就是当前节点,把当前节点放到实例对象上*/}
<input ref={c => this.input2 = c} onBlur={this.showData2} type="text" placeholder="失去焦点提示数据" />
</div>
)
}
}
// 渲染组件到页面
ReactDOM.render(<Demo />, document.querySelector('#test'))
</script>
使用createRef()
createRef 是 React v16.3 新增的API,允许我们访问 DOM 节点或在 render 方法中创建的 React 元素。
Refs 是使用 React.createRef() 创建的,并通过 ref 属性附加到 React 元素。
Refs 通常在 React 组件的构造函数中定义,或者作为函数组件顶层的变量定义,然后附加到 render() 函数中的元素。
<script type="text/babel">
// 定义函数组件
class Demo extends React.Component {
myRef = React.createRef()
showData3 = () => {
console.log(this.myRef.current.value);
}
render() {
return (
<div>
{/* 使用createRef()来创建ref*/}
<input ref={this.myRef} onFocus={this.showData3} type="text" placeholder="获取焦点提示数据" />
</div>
)
}
}
// 渲染组件到页面
ReactDOM.render(<Demo />, document.querySelector('#test'))
</script>
Refs注意点
- 不要过度使用Refs,如果可以通过声明实现,则尽量避免使用refs;
- 不能在函数式组件上使用ref属性(就是function定义的组件,不是class),因为它们没有实例;
- ref 的更新会发生在componentDidMount 或 componentDidUpdate 生命周期钩子之前。所以不能在组件卸载的时候直接使用ref的react元素,React 会在组件卸载时将ref 改回 null。