乐趣区

关于前端:通过vue3学习react17一-组件之间方法调用ts

学习 react 的时候, 自身我工作中应用的都是 vue, 应用想通过 vue 的应用去解析 react 的写法,

发现 vue3 的写法有挺多种的,和 react17 也有不同的写法

于是就产生这篇文章, 有哪些不正确心愿大佬斧正

Vue(setup) 写法

父组件 (Parent.vue)
# Parent.vue
<template>
  <div>
    <p>{{count}}</p>
    <Child :count="count" @setCount="setCount"></Child>
  </div>
</template>

<script setup lang="ts">
import {ref} from "vue";
import Child from "./Child.vue";

let count = ref(0);
function setCount(param: typeof count.value) {count.value = param;}
</script>
子组件 (child.vue)
# Child.vue
<template>
  <div>
    <button @click="emit('setCount', ++count)"> 按钮 </button>
  </div>
</template>

<script setup lang="ts">
defineProps<{count: number}>();

const emit = defineEmits<{(e: "setCount", count: number): void;
}>();
</script>
子组件 (newChild.vue) 第二种写法
# newChild.vue
<template>
  <div>
    <button @click="$emit('setCount', count + 1)"> 按钮 2 </button>
  </div>
</template>

<script lang="ts">
import {ref, defineComponent} from "vue";

export default defineComponent({
  props: {
    count: {
      type: Number,
      require: true,
      default: 0,
    },
  },
  emits: ["setCount"],
});
</script>

React 写法

父组件 (Parent.tsx)
# Parent.tsx
import {useState} from "react";
import Child from "./newChild";

function Parent() {let [count, setCount] = useState(0);
  return (
    <div>
      <p>{count}</p>
      <Child count={count} setCount={setCount}></Child>
    </div>
  );
}

export default Parent;
子组件 (Child.ts)
# Child.ts
interface ChildInterface {
  count: number;
  setCount: (params: ChildInterface["count"]) => void;
}

interface ChildProps extends React.FC<ChildInterface> {}

const Child: ChildProps = (props) => {let { count, setCount} = props;
  return (
    <div>
      <button
        onClick={() => {setCount(++count);
        }}
      >
        按钮
      </button>
    </div>
  );
};

export default Child;
子组件 (newChild.ts) 第二种写法
# newChild.ts
import React from "react";

interface ChildProps {
  count: number;
  setCount: (params: ChildProps["count"]) => void;
}

class Child extends React.Component<ChildProps> {render() {let { count, setCount} = this.props;
    return (
      <div>
        <button
          onClick={() => {setCount(++count);
          }}
        >
          按钮
        </button>
      </div>
    );
  }
}

export default Child;
退出移动版