繁体   English   中英

如何在我的 React Typescript 计数器中使用类型接口支撑钻头?

[英]How to prop drill with type interfaces in my React Typescript counter?

我正在制作一个简单的计数器应用程序来跟踪我玩的数字纸牌游戏。 我正在将父母的道具传递给我的孩子,但道具没有被传递。 我认为修复只是在我在界面中创建的属性的末尾加上一个问号(?),但这似乎不是最优的。 代码有效,我只是在主文件和组件文件中重复数据,我不想这样做。

我的 app.tsx:

import React from 'react'
import './App.css'
import Counter from './components/Counter'

function App() {
  return (
    <div className="App">
      <Counter
        deckName="elusive burn"
        winPercentage={123}
        losses={6}
        wins={7}
      />
    </div>
  )
}

export default App

我的 Counter.tsx:

import React, { useState } from 'react'

// add a ? after the type name if you want any one of these to be optional, ex: wins?
interface Props {
  deckName: string
  wins: number
  losses: number
  winPercentage: number
}

const Counter: React.FC<Props> = () => {
  const [counter] = useState<Props>({
    deckName: '',
    wins: 0,
    losses: 0,
    winPercentage: 0,
  })

  return (
    <div>
      <p>Deck Name: {counter.deckName} </p>
      <p>wins: {counter.wins} </p>
      <p>losses: {counter.losses} </p>
      <p>Win Percentage: {counter.winPercentage}% </p>
    </div>
  )
}

export default Counter

谢谢参观!

你为什么在这里使用useState 您从props收到所有需要的信息,因此请直接从那里获取。 然后我想你会看到没有多余的代码。

// Counter.tsx
import React from 'react'

// add a ? after the type name if you want any one of these to be optional, ex: wins?
interface Props {
  deckName: string
  wins: number
  losses: number
  winPercentage: number
}

const Counter: React.FC<Props> = ({ deckName, wins, losses, winPercentage }: Props) => {
  return (
    <div>
      <p>Deck Name: {deckName} </p>
      <p>wins: {wins} </p>
      <p>losses: {losses} </p>
      <p>Win Percentage: {winPercentage}% </p>
    </div>
  )
}

export default Counter

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM