Java教程

unstated-next 使用

本文主要是介绍unstated-next 使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
//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>
  )
}
这篇关于unstated-next 使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!