【发布时间】:2017-02-23 06:17:07
【问题描述】:
针对 TypeScript 2.1 更新
TypeScript 2.1 now supports object spread/rest,因此不再需要解决方法!
原始问题
TypeScript 支持 JSX spread attributes,它在 React 中常用来将 HTML 属性从组件传递到呈现的 HTML 元素:
interface LinkProps extends React.HTMLAttributes {
textToDisplay: string;
}
class Link extends React.Component<LinkProps, {}> {
public render():JSX.Element {
return (
<a {...this.props}>{this.props.textToDisplay}</a>
);
}
}
<Link textToDisplay="Search" href="http://google.com" />
然而,React 引入了warning if you pass any unknown props to an HTML element。上面的例子会产生一个 React 运行时警告 textToDisplay 是 <a> 的一个未知属性。对于像这个例子这样的案例,建议的解决方案是使用object rest properties 提取您的自定义道具并将其余部分用于 JSX 传播属性:
const {textToDisplay, ...htmlProps} = this.props;
return (
<a {...htmlProps}>{textToDisplay}</a>
);
但是 TypeScript 还不支持这种语法。我知道希望有一天we will be able to do this in TypeScript。(更新:TS 2.1 now supports object spread/rest!你为什么还在读这个??)解决方法?我正在寻找一种不会影响类型安全的解决方案,并且发现它非常困难。例如我可以这样做:
const customProps = ["textDoDisplay", "otherCustomProp", "etc"];
const htmlProps:HTMLAttributes = Object.assign({}, this.props);
customProps.forEach(prop => delete htmlProps[prop]);
但这需要使用未针对实际道具进行验证的字符串属性名称,因此容易出现拼写错误和不良的 IDE 支持。有没有更好的方法可以做到这一点?
【问题讨论】:
-
请注意,您正在寻找的语法现在可用
-
@KyleGobel 真的,我很高兴。 :) 这个问题应该被删除吗?
-
“TypeScript 2.1 现在支持对象传播/休息,因此不再需要变通方法!”你怎么用这个?!!
-
@gyozokudor 只需使用 TypeScript 2.1 或更高版本(现在最高 3.4!)并使用原始示例:
const {textToDisplay, ...htmlProps} = this.props
标签: reactjs typescript