学习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;
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。