使用 React Hooks 以及 Typescript,采用函数式编程风格编写组件
Todo 组件
Todo.tsx
import React, { useState } from 'react'
interface TodoItem {
label: string;
date: string;
}
type TodoList = TodoItem[];
interface TodoPropType {
todoList: TodoList;
onTodoListChange: (newTodoList: TodoList) => void;
}
const Todo: React.FC<TodoPropType> = ({ todoList, onTodoListChange }) => {
const [item, setItem] = useState<TodoItem>({
label: '',
date: ''
})
const addTodoItem = () => {
const newTodoList = [...todoList, item]
onTodoListChange(newTodoList)
}
const removeItem = (idx: number) => {
onTodoListChange([...todoList.slice(0, idx), ...todoList.slice(idx + 1)])
}
const itemChange = (prop: keyof TodoItem, value: string) => {
setItem({
...item,
[prop]: value
})
}
return (
<>
<ul>
{todoList.map(({ label, date }, i) =>
<li key={i}>
<strong>
Label:
</strong>
{label}
<strong>
Date:
</strong>
{ date }
<button onClick={() => removeItem(i)}> - </button>
</li>
)}
</ul>
<input type="text" value={item.label} onChange={e => itemChange('label', e.target.value)} />
<input type="date" value={item.date} onChange={e => itemChange('date', e.target.value)} />
<button onClick={() => addTodoItem()}> + </button>
</>
)
}
export { Todo, TodoItem }
父组件
Parent.tsx
import React, { useState } from 'react'
import { Todo, TodoList } from '/path/to/Todo'
export { Page }
const Page = () => {
const [todoList, setTodoList] = useState<TodoList>([{
label: 'Event1',
date: '2021-07-01'
}])
return (
<>
<h1>Welcome</h1>
<Todo todoList={todoList} onTodoListChange={setTodoList} />
</>
)
}
提个小建议
好像编辑器不支持 jsx
跟 tsx
语法高亮,希望可以支持 @88250
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于