【问题标题】:TypeScript error in passing props to child component in react将道具传递给反应中的子组件时出现TypeScript错误
【发布时间】:2021-02-01 11:12:58
【问题描述】:

我正在使用 react + typescript 构建费用跟踪器应用程序

expense_type.ts

    export  type IState = {
    id : number,
    text : string,
    amount : number

}

export type IinitialStateType =  {
    transactions : IState[]
}

export type IActions =  {
    type : string,
    payload : any
}

export type contextProps = {
    transactions : IState[];
    addTransaction: (trans: IState) => void;
    deleteTransaction: (id: number) => void;
}

然后我使用了 API Context 和 reducer 并在 Global State 文件中初始化了我的初始状态

GlobalState.tsx

import React , {createContext,useReducer} from 'react'
import {IinitialStateType,contextProps} from '../Types/expense_type'
import AppReducer from './AppReducer'

const initailState : IinitialStateType = {
    transactions : [
          { id: 1, text: 'Flower', amount: -20 },
          { id: 2, text: 'Salary', amount: 300 },
          { id: 3, text: 'Book', amount: -10 },
          { id: 4, text: 'Camera', amount: 150 }
    ]
}

export const GlobalContext = createContext<Partial<contextProps>>({})

export const GlobalProvider : React.FC = ({children}) : JSX.Element => {

    const [state,dispatch] = useReducer(AppReducer,initailState)
    
    return(
        <GlobalContext.Provider value={{
            transactions : state.transactions
        }}>
            {children}
        </GlobalContext.Provider>
    )
}

然后我在 TransactionList.tsx 组件中使用上下文并映射所有初始状态值并将这些值传递给这些值正在接收的子组件 Transaction.tsx

TransactionList.tsx

import React ,{useContext}from 'react'
import {GlobalContext} from './../Context/GlobalState'
import {contextProps,IinitialStateType,IState} from '../Types/expense_type'
import {Transaction} from './Transaction'

export const TransactionList : React.FC = () : JSX.Element => {

    const {transactions} : any = useContext(GlobalContext)
    return (
        <>   
            <h3>History</h3>
            <ul className="list">
                { 
                    transactions.map( (transaction : IState , index : number)  => 
                        (<Transaction key={index} transaction={transaction} />
                    )) 
                 }
            </ul>
        
        </>
    )
}

Transaction.tsx

    import React from 'react'
    import {IinitialStateType} from '../Types/expense_type'
    export const Transaction : React.FC<IinitialStateType>= (props : any) : JSX.Element => {

    let sign : string = props.transaction.amount > 0 ? '+' : '-'

    return (
        <>
            <li className={props.transaction.ammount < 0 ? "minus" : "plus"}>
                {props.transaction.text}{" "}
                <span>
                    {sign}${Math.abs(props.transaction.ammount)}
                </span>
                <button
                    className="btn-delete"
                >
                    x
                </button>
            </li>
        </>
    )
}

但是在编译时它会在 TransactionList.tsx 文件中出现错误

TypeScript error in C:/Users/Abdul Rehman Aziz/Desktop/New folder/expense-tracker-ts/src/Components/TransactionList.tsx(14,88): Type '{ key: number; transaction: IState; }' is not assignable to type 'IntrinsicAttributes & IState & { children?: ReactNode; }'.   Property 'transaction' does not exist on type 'IntrinsicAttributes & IState & { children?: ReactNode; }'.  TS2322

    12 |             <h3>History</h3>
    13 |             <ul className="list">
  > 14 |                  { transactions.map( transaction => (<Transaction key={transaction.id} transaction={transaction} />)) }
       |                                                                                        ^
    15 |             </ul>
    16 |         </>
    17 |         </>

【问题讨论】:

  • 我认为对您有用的一条评论是避免像在 TransactionList 中那样使用索引作为组件的键,因为这是默认行为,如果您使用它来显示列表可以突变的,你会遇到问题。您的问题是您正在传递一个名为 Transaction 的道具,该道具在类型 IinitialStateType 上不存在

标签: reactjs typescript


【解决方案1】:

你必须为 React.FC 指定 Props 的类型,而不是 state。像这样:

export const Transaction: React.FC<{ transaction: IState }> = (
  props: any

我还做了一个工作示例:https://codesandbox.io/s/focused-sanderson-e6zlm?file=/src/App.tsx

【讨论】:

    【解决方案2】:

    您的 Transaction 组件需要 IinitialStateType 类型的道具,并且根据您对该类型的定义,它没有称为 transaction 的属性,并且它不接收一个项目,而是一个数组。如果您将 Transaction 组件中的道具类型更改为类似

    export const Transaction : React.FC<IState>= (props : any) : JSX.Element => {
    ...
    }
    

    应该有帮助。

    【讨论】:

      猜你喜欢
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      • 2017-10-20
      • 2020-09-10
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 2019-07-29
      相关资源
      最近更新 更多