Parent component (I deleted some irrelavant code):
import React, { useState, useCallback, useMemo, useRef, useEffect } from 'react
import InputItem from 'src/components/InputItem'
let tokenRef = useRef(null)
return (
<InputItem
ref={tokenRef}
placeHolder="xxxx"
/>
)
}
const mapStateToProps = ({ form }) => {
return {
form
}
}
const mapDispatchToProps = (dispatch, props) => {
return {}
}
export default connect(mapStateToProps, mapDispatchToProps)(Header)
Child function component (I deleted some irrelavant code):
import React, {
useState,
useRef,
useMemo,
forwardRef,
useImperativeHandle,
Ref
} from 'react'
import './index.less'
import { connect } from 'react-redux'
interface IOwnProps {
placeHolder?: string
}
interface IStateProps {
form: any
}
interface IDispatchProps {
}
type IProps = IStateProps & IOwnProps & IDispatchProps
const InputItem = forwardRef((props: IProps, ref: Ref<any>) => {
const {
placeHolder,
} = props
const ipt = useRef(null)
useImperativeHandle(ref, () => {
return {
value: ipt.current.value,
focus: () => ipt.current.focus()
}
})
return (
<div className="input-item" style={style}>
<input
type="text"
placeholder={placeHolder}
ref={ipt}
></input>
</div>
)
})
const mapStateToProps = ({ form }) => {}
const mapDispatchToProps = (dispatch, props) => {}
export default connect(mapStateToProps, mapDispatchToProps)(InputItem)
I get a warning which says I can't use a ref in a function component. However, I did use forwardRef in my child component to avoid such problems and it still won't work change useRef value to the wrapped component.
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?