【发布时间】:2017-05-15 23:16:01
【问题描述】:
我不知道如何使用 TypeScript 设置我的 React 组件的状态。
- 我正在制作一个简单的待办事项列表
- 我有一个用于整个列表的组件:
TodoList - 我想在列表中添加一些可以玩的项目
- 我想我会发送一个简单的数组作为
TodoList组件的道具,然后立即将其设置为状态,这样我就有了一些工作要做
import * as React from "react";
import { TodoItem, ITodoItem } from "../TodoItem";
interface ITodoListProps {
items: ITodoItem[];
}
interface ITodoListState {
stateItems: ITodoItem[];
}
export class TodoList extends React.Component<ITodoListProps, Partial<ITodoListState>> {
constructor(props: ITodoListProps) {
super(props);
// Trouble figuring this part out
// I'd like to set the state to the list from the
// props, as a seed.
this.setState({
stateItems: this.state.stateItems
});
}
public render() {
return (
<div>
<ul>
// This should probably be displaying the items from the state, and not the props.
{this.props.items.map((todo, i) => {
return <TodoItem key={i} name={todo.name} />
})}
</ul>
</div>
);
}
}
【问题讨论】:
标签: reactjs typescript