【问题标题】:Error: "Type '{}' is missing the following properties from type错误:“类型“{}”缺少类型中的以下属性
【发布时间】:2020-03-18 02:00:31
【问题描述】:

我正在制作一个待办事项列表,但出现此错误 “Type '{ id: number; text: string; }' is missing the following properties from type 'Props': item, handleDelete”。我不知道如何解决这个问题了。谢谢

来自 App.tsx

import React, { useState } from 'react'
import TodoComponent from './TodoComponent'

interface Todo {
    id: number
    text: string
}

function App() {
    const [inputText, setInputText] = useState<string>('')
    const [todoArray, setTodoArray] = useState<Array<Todo>>([{ id: 0, text: '' }])
    const [count, setCount] = useState<number>(1)

    const handleClick = () => {
        if (inputText !== '') setCount(count + 1)
        setTodoArray([...todoArray, { id: count, text: inputText }])
        setInputText('')
    }

    const handleDelete = (id: number) => {
        console.log('click', id)
    }

    return (
        <div>
            <input type="text" value={inputText} onChange={e => setInputText(e.target.value)} />
            <button onClick={handleClick}>Add</button>

            {todoArray.map(item => {
                return <TodoComponent {...item} {...handleDelete}/>
            })}
        </div>
    )
}

export default App

来自 TodoComponent.tsx

import React from 'react'

interface Props {
    item: {id: number, text: string}
    handleDelete: (id: number) => void
}

function TodoComponent(todo: Props) {
    return (
        <div>
            {todo.item.text}
            {todo.item.text !== '' && <button onClick={() => todo.handleDelete(todo.item.id)}>x</button>}
        </div>
    )
}

export default TodoComponent

【问题讨论】:

    标签: reactjs typescript react-hooks


    【解决方案1】:

    你必须这样传递道具:

    {todoArray.map(item => {
                return <TodoComponent item={item} handleDelete={handleDelete} />
    })}
    

    【讨论】:

    • 是的,就是这样,谢谢。我之前尝试过,但是遇到了一些错误,所以我在堆栈上发现我应该使用这种语法:{...smth} 并且仍然遇到另一个错误哈哈
    • 没问题,当你使用扩展运算符传递对象时,它会提取属性(键,值)并传递给 Props,因此如果 Props 接口与传递的对象具有相同的属性,那么它将工作正常。
    猜你喜欢
    • 2020-05-23
    • 2021-01-05
    • 2020-04-07
    • 1970-01-01
    • 2021-04-20
    • 2021-07-29
    • 1970-01-01
    • 2023-02-07
    • 2020-10-28
    相关资源
    最近更新 更多