错误:“类型'{}'缺少类型的以下属性

时间:2020-03-17 17:46:38

标签: reactjs typescript react-hooks

我正在创建一个待办事项列表,但出现此错误“类型'{id:数字;文本:字符串;}'缺少类型'道具'的以下属性:item,handleDelete” < / em>。我不知道该如何解决。谢谢

来自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

1 个答案:

答案 0 :(得分:0)

您必须以这种方式传递道具:

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