React Hooks + ts 父组件调用子组件方法 笔记
父组件:Login.tsx 子组件:PhoneInput.tsx 父组件点击登录按钮时调用子组件检查手机号码格式的方法
父组件代码
//Login.tsx
import React,{
useState,useRef} from react
import PhoneInput from ../components/phoneInput/PhoneInput
interface PhoneRef{
checkPhone:(phone:number) => boolean
}
function Login(){
let [phone,setPhone] = useState<number>()
const phoneRef = useRef<PhoneRef>()
const loginFunc = () => {
console.log(phoneRef.current?.checkPhone(phone as number))
}
return(
<div>
<PhoneInput
//这里直接传ref参数 子组件不能通过props.ref拿到,只理解到ref是rect的内置对象,不会被当成props传入子组件。后续需要再多了解原理,
onRef={
phoneRef}
></PhoneInput>
<button className="button" onClick={
() => {
loginFunc()}}> 登 录</button>
</div>
)
}
export default Login
子组件代码
//PhoneInput.tsx
import React,{
PropsWithChildren, useImperativeHandle} from react
interface PhoneProps {
onRef: React.MutableRefObject<object | undefined>
}
const PhoneInput: React.FC<PhoneProps>= (props: PropsWithChildren<PhoneProps>) => {
let [phone,setPhone] = useState<number>()
useImperativeHandle(props.onRef,() => {
return {
checkPhone : (phone:Number):Boolean => {
return /^[1][0-9]{10}$/.test(String(phone))
}
}
})
return (
<div className="group">
<input
placeholder="手机号"
type="search"
className="input"
value={
phone}
/>
</div>
)
}
export default PhoneInput
不相关的代码都被删掉了,这些东西基本上都是百度甚至看着报错类型信息写出来的,所以原理基本不了解,只做记录,后面要加强知识点学习。
