react中父组件如何直接调用子组件的方法和属性,以及对比vue3.0父组件调用子组件的方法和属性

react中父组件如何直接调用子组件的方法和属性,以及对比vue3.0父组件调用子组件的方法和属性

    • react hook
    • vue setup
      • 父组件
      • 子组件

react hook

forwardRef(render)
useImperativeHandle(ref, createHandle, dependencies?)

import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from "react";

const ChildrenComponents = forwardRef(function ChildrenComponents(props, ref) {
  //useImperativeHandle类似于vue3.0的defineExpose,把子组件中要暴漏给父组件属性或方法,以对象的方式抛出去
  useImperativeHandle(
    ref,
    () => {
      return {
        initList,
        exposeParamter() {
          return {
            defaultTitleRef,
          };
        },
        defaultTitleRef,
        name,
        list,
      };
    },
    []
  );

  const defaultTitleRef = "我是子组件";

  let [name, setName] = useState("工藤新一");

  let [list, setList] = useState([
    {
      name: "工藤新一",
      sex: "男",
    },
    {
      name: "毛利兰",
      sex: "女",
    },
  ]);
  //初始化
  function initList() {
    console.log("[初始化子组件数据]");
  }

  function sendMessage() {
    // 类似于vue3.0的defineEmits
    props.click("点击子组件给父组件传值");
  }

  useEffect(() => {
    console.log("[useEffect-子组件]", props);
  }, []);
  return (
    <>
      

我是子组件:{name}


点击子组件给父组件传值 ); }); function Forward() { const childrenRef = useRef(null); let [title, setTitle] = useState("我想操作子组件的方法和属性"); let [defaultName, setDefaultName] = useState(""); let [list, setList] = useState([]); function getMessageHandle(params) { console.log("[我接收了子组件的传值]", params); console.log(childrenRef.current.list); } useEffect(() => { console.log("[useEffect-父组件如何直接调用子组件的方法和属性]"); childrenRef.current.initList(); console.log("", childrenRef.current.exposeParamter().defaultTitleRef); console.log("[name]", childrenRef.current.name); setDefaultName(childrenRef.current.defaultTitleRef); setList(childrenRef.current.list); }, []); return ( <>

forwardRef:我是父组件

{defaultName}

{/* react通过标签的属性传值 */} {list.map((item, index) => { return (

{item.name}-{item.sex}

); })} ); } export default Forward;

vue setup

父组件






子组件






你可能感兴趣的:(React,react.js,javascript,vue.js)