【发布时间】:2020-07-08 03:05:15
【问题描述】:
这些天我一直在用 Typescript 练习 React。
我的 PropsType 如下
export type PropType = {
ingredientAdded: (type: keyof IngredientType) => void;
}
和
const buildControl: React.FunctionComponent<PropType> = (props) => (
<div className={classes.BuildControl}>
<div className={classes.Label}>{props.label}</div>
<button className={classes.Less}>Less</button>
<button className={classes.More} onClick={props.ingredientAdded as any}>More</button>
</div>
);
作为身体。
这里的问题是我不能通过 onClick={props.ingredientAdded} 而不强制转换。
当我查看 onClick 类型时,它给了我
onClick?: MouseEventHandler<T>;
type MouseEventHandler<T = Element> = EventHandler<MouseEvent<T>>;
似乎ingredientAdded: (type: keyof IngredientType) => void; 函数类型对onClick 无效。
不管怎样都行。
我的问题是在这里进行类型检查而不是强制转换为 any
的正确方法是什么编辑
父组件传递函数。
type PropsType = {
ingredientAdded(type: keyof IngredientType): void;
ingredientRemoved(type: keyof IngredientType): void;
}
const controls: { label: string, type: keyof IngredientType }[] = [
{ label: 'Salad', type: 'salad' },
{ label: 'Bacon', type: 'bacon' },
{ label: 'Cheese', type: 'cheese' },
{ label: 'Meat', type: 'meat' },
];
const buildControls: React.FunctionComponent<PropsType> = (props) => (
<div className={classes.BuildControls}>
{controls.map(ctrl => (
<BuildControl
ingredientAdded={() => props.ingredientAdded(ctrl.type)}
ingredientRemoved={() => props.ingredientRemoved(ctrl.type)}
key={ctrl.label} label={ctrl.label} />
))}
</div>
);
export default buildControls;
【问题讨论】:
-
问题是,1)
props.ingredientAdded是否需要点击事件对象 2)它是如何得到它的type参数的? -
answer 1) 不需要点击事件处理程序。类型参数是从父组件传递的。我将编辑代码
标签: reactjs typescript