在父组件中拿到子组件某个标签,限制父组件可以任意操作子组件的dom元素

    //b.jsx

    1. import React,{forwardRef,useRef,useImperativeHandle } from 'react'
    2. const B=forwardRef((props,ref)=>{
    3. const inputRef=useRef(null)
    4. useImperativeHandle(ref,()=>({
    5. focus: () => {
    6. inputRef.current && inputRef.current.focus();
    7. },
    8. talk: () => {
    9. console.log('hello, world!');
    10. }
    11. }))
    12. return (
    13. <input ref={inputRef}></input>
    14. )
    15. })
    16. export default B

    a.jsx

    1. import React, { useRef } from 'react';
    2. import B from "./B"
    3. const A=()=>{
    4. const refContainer = useRef(null);
    5. const changeInput = () => {
    6. refContainer.current && refContainer.current.focus()
    7. }
    8. const talk = () => {
    9. refContainer.current && refContainer.current.talk()
    10. }
    11. return <div >
    12. <button onClick={changeInput}>changeInput</button>
    13. <button onClick={talk}>talk</button>
    14. <B ref={refContainer}></B>
    15. </div>
    16. }
    17. export default A