//count-context.tsx
import { useState } from 'react'
import { createContainer, useContainer } from 'unstated-next'
interface CounterProps {
count: number
increment: () => void
decrement: () => void
}
function Counter(initialState = 0): CounterProps {
const [count, setCount] = useState(initialState)
const decrement = () => setCount(count - 1)
const increment = () => setCount(count + 1)
return { count, decrement, increment }
}
export const CounterContainer = createContainer(Counter)
export function useCounter() {
return useContainer(CounterContainer)
}
import { useCounter, CounterContainer } from './count-context'
function Counter1() {
const { count, decrement, increment } = useCounter()
return (
<div>
<button onClick={decrement}>-</button>
<span>1.you click {count} times</span>
<button onClick={increment}>+</button>
</div>
)
}
function Counter2() {
const { count, decrement, increment } = useCounter()
return (
<div>
<button onClick={decrement}>-</button>
<span>2.you click {count} times</span>
<button onClick={increment}>+</button>
</div>
)
}
export default function Index() {
return (
<CounterContainer.Provider initialState={10}>
<Counter1 />
<Counter2 />
<div>
<CounterContainer.Provider>
<Counter1 />
<Counter2 />
</CounterContainer.Provider>
</div>
</CounterContainer.Provider>
)
}
标签:count,function,const,unstated,next,increment,使用,return,decrement
From: https://www.cnblogs.com/samsara-yx/p/16639635.html