在父组件中拿到子组件某个标签,限制父组件可以任意操作子组件的dom元素
//b.jsx
import React,{forwardRef,useRef,useImperativeHandle } from 'react'
const B=forwardRef((props,ref)=>{
const inputRef=useRef(null)
useImperativeHandle(ref,()=>({
focus: () => {
inputRef.current && inputRef.current.focus();
},
talk: () => {
console.log('hello, world!');
}
}))
return (
<input ref={inputRef}></input>
)
})
export default B
a.jsx
import React, { useRef } from 'react';
import B from "./B"
const A=()=>{
const refContainer = useRef(null);
const changeInput = () => {
refContainer.current && refContainer.current.focus()
}
const talk = () => {
refContainer.current && refContainer.current.talk()
}
return <div >
<button onClick={changeInput}>changeInput</button>
<button onClick={talk}>talk</button>
<B ref={refContainer}></B>
</div>
}
export default A