React Hook parent component subassembly acquired data / function

We know react, commonly used props to achieve sub-component data transfer to the parent component, but the parent component sub-assemblies function call is not commonly used. In fact, said the ref is not the best choice, but think of lazy and do not learn redux, the Internet to find a lot of tutorials, or else hook speaking too little, or else his son tell the component silly, so he had another on the document eating a little documentation, schooling a bit api hook the other.
Here we need to use useImperativeHandlethis api, it is functional form

useImperativeHandle(ref, createHandle, [deps])

In fact, this is also a form of api ref, but the equivalent of doing a certain amount of optimization, you can choose two steps allow only certain sub-components exposed to the api parent component, according to the method given in the documents and other blog, a total of :

  1. The ref is transmitted to the subassembly
  2. Require the use of sub-components packaged forwardRef

Subassemblies MyWorldMap

 const mapRef = useRef(null);
    useImperativeHandle(ref, () => {

        return {
            //clickSwitch是子组件暴露的函数
            clickSwitch() {
             
                if(type == 1){
                    initChinaMap();
                    setType(2);
                }else{
                    initWordMap();
                    setType(1);
                }
              
            }
        }
    })

//你的return内容,注意ref

    return(
        <React.Fragment>

            <div id={"myWorldMap"} style={{ width: "800px", height: "400px" }}  ref={mapRef}></div>

        </React.Fragment>


    )
}


//最后要配合forwardRef
MyWorldMap = forwardRef(MyWorldMap);
export default MyWorldMap;

Note: ref is the time subcomponent declaration passed in, that is,

function MyWorldMap (props,ref){
//..你的代码
}

//export...

In fact, the official document to come out examples are:

function FancyInput(props, ref) {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }));
  return <input ref={inputRef} ... />;
}
FancyInput = forwardRef(FancyInput);

Both methods are possible

Parent component MyTrip

const myWordMapRef = useRef();

return(
  //省略一些代码,注意ref
 <MyWorldMap proData = { myMapData} handleMapClick = {handleMapClick.bind(this)} ref={myWordMapRef}>

 </MyWorldMap>
<div className={styles["mapButton-wrap"]}>
       <ButtonGroup>
               <Button onClick={() => myWordMapRef.current.clickSwitch()}>Switch</Button>
               <Button onClick={()=>clickAll() }>All</Button>
        </ButtonGroup>
 </div>
)

Now you can by the parent component which myWordMapRef.current.clickSwitch()calls the function

Guess you like

Origin www.cnblogs.com/yuyuan-bb/p/11478837.html