之前运用React.forwardRef一直没法运用于React高阶组件中,近来终究捣鼓出来了,因而记录下来。
症结点就是React.forwardRef的API中ref必需指向dom元素而不是React组件。codepen实例请划到底部。
一、React.forwardRef运用示例
下面就是运用到React组件的毛病示例:
const A=React.forwardRef((props,ref)=><B {...props} ref={ref}/>)
这就是我之前经常犯的毛病, 这里的ref是没法见效的。
前面提到ref必需指向dom元素,那末准确要领就运用而生:
const A=React.forwardRef((props,ref)=>(
<div ref={ref}>
<B {...props} />
</div>
))
二、React.forwardRef运用到高阶组件中
2.1. withComponent范例的高阶组件【1】
import React from 'react'
import A from './a.jsx'
import PropTypes from 'prop-types';
function withA(Component){
const ForWardedComponent = React.forwardRef((props, ref) => <div ref={ref}>
<Component {...props} />
</div>);
class MidComponent extends React.Component {
render() {
const props = this.props
return (
<A {...props}>
<ForWardedComponent ref={props.forwardedRef} {...props}/>
</A>
)
}
}
//对MidComponent组件属性举行范例经查
MidComponent.propTypes = {
forwardedRef: PropTypes.object,
}
return MidComponent
}
exports.withA=withA
如许,在上述示例的组件A中,A的周期componentDidMount() 挪用 this.props.forwardedRef.current ,指向的就是上述示例中ForWardedComponent对应的dom元素。
是B组件对应的dom的父元素,而不是该dom
在a.jsx中某处:
componentDidMount(){
console.log(this.props.forwardedRef.current)
}
末了运用实例:
import React from 'react'
import ReactDOM from 'react-dom'
//假定withA存储于withA.js文件。
import {withA} from './withA.js'
const B=()=><h2>hello world</h2>
const B2=withA(B)
class App extends React.Component {
constructor(props) {
super(props)
this.forwardedRef=React.creactRef()
}
render() {
return <div>
<B2 forwardedRef={this.forwardedRef}/>
</div>
}
}
ReactDOM.render(<App/>,document.getElementById('app'))
2.2 地道的高阶组件(Parent-Child)
【1】中并非React组件,只是一个React组件为参数的函数,挪用今后才成为React组件。那末直接写入一个Parent组件又该怎样呢?
import React from 'react'
import A from './a.jsx'
import PropTypes from 'prop-types';
function AasParent(props){
const ForWardedComponent = React.forwardRef((props, ref) => <div ref={ref}>
{props.children}
</div>);
return (
<A {...props}>
<ForWardedComponent ref={props.forwardedRef} {...props}/>
</A>)
}
AasParent.propTypes = {
forwardedRef: PropTypes.object,
}
module.exports=AasParent
末了运用实例:
import React from 'react'
import ReactDOM from 'react-dom'
//假定AasParent存储于AasParent.jsx文件。注重与【1】中的区分
import AasParent from './AasParent.jsx'
const B=(props)=><h2>{props.greetings}</h2>
class App extends React.Component {
constructor(props) {
super(props)
this.forwardedRef=React.creactRef()
}
render() {
return <AasParent forwardedRef={this.forwardedRef}>
<B2 greetings="你好,Melo"/>
</AasParent>
}
}
ReactDOM.render(<App/>,document.getElementById('app'))
三、总结
1.React.forwardRef的API中ref必需指向dom元素而不是React组件。
2.在【1】的组件A中,A的周期componentDidMount() 挪用 this.props.forwardedRef.current
,指向的就是【1】中ForWardedComponent
对应的dom元素。是【1】中B组件对应的dom的父dom元素,而不是该dom。
3.codepen实例