目录
refs转发
Ref 转发是一项将 ref 自动地通过组件传递到其一子组件的技巧,Ref 转发使组件可以像暴露自己的 ref 一样暴露子组件的 ref。
下面是几个适合使用 refs 的情况:
- 管理焦点,文本选择或媒体播放。
- 触发强制动画。
- 集成第三方 DOM 库。
避免使用 refs 来做任何可以通过声明式实现来完成的事情。
ref 的作用是获取实例,可能是 DOM 实例,也可能是 ClassComponent 的实例,但是不能在函数组件上使用 ref 属性,因为函数组件没有实例
ref使用中的问题
- ref 不能通过props进行传递,和key一样。
- 将组件包装成高阶组件(HOC),无法通过ref去获取包装前的组件实例
- 如果目标对象时函数组件,传递ref会报错,那么怎样才能使用ref去获取函数组件呢?
1、问题:HOC中ref不能向下传递
// Log.js
import React, {
Component } from 'react'
const Log = MyComponent => {
class Logout extends Component {
componentDidMount() {
console.log('did mount')
}
componentDidUpdate(prevProps, prevState) {
console.log('did update')
}
render() {
return (<MyComponent {
...this.props} />);
}
}
return Logout
}
export default Log;
访问ref时,实际指向的是Logout容器组件,并不是包装前的组件Detail
import log from '../Log'
import Detail from '../Detail'
const Logout = log(Detail)
<Logout ref={
ref} />
2、ref不能在函数组件上使用,会报错
// 函数组件
function MyFunctionComponent() {
return <input />;
}
class Parent extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
render() {
// This will *not* work!
return