在 React 组件中使用 Vue Composition API
在 React 组件中使用 Vue Composition API
npm i reactivue我非常喜欢 Vue Composition API 和其 反应性系统,
但 React 中的 函数式组件也与 TypeScript 相得益彰。
为什么不将它们结合使用呢?
…为了重用组合逻辑,createSetup 提供了一个工厂,用于创建自己的钩子。
// mySetup.ts
import { createSetup, ref, computed, onUnmounted } from 'reactivue'
export interface Props {
value: number
}
// create a custom hook that can be reused
export const useMySetup = createSetup(
(props: Props) => {
const counter = ref(props.value)
const doubled = computed(() => counter.value * 2)
const inc = () => counter.value += 1
onUnmounted(() => console.log('Goodbye World'))
return { counter, doubled, inc }
},
)// Counter.tsx
import React from 'react'
import { useMySetup, Props } from './mySetup'
export const Counter = (props: Props) => {
const { counter, doubled, inc } = useMySetup(props)
const { counter: counter2, doubled: doubled2, inc: inc2 } = useMySetup({ value: 10 })
return (
<button onClick={inc}>Increase</button>
<br/>
<button onClick={inc2}>Increase</button>
</div>
)
}要在 Preact 应用中使用 reactivue,只需将 reactivue 导入替换为 reactivue/preact
import { h } from 'preact'
- 导入 { defineComponent, ref, computed, onUnmounted } 从 'React'
<a href="https://www.npmjs.com/package/reactivue"></a>
<a href="https://bundlephobia.com/result?p=reactivue@latest"></a>暂无开放 Issues,或尚未同步最近议题。