最佳答案
TypeScript 2.1现在支持对象扩展/rest ,因此不再需要变通方法!
TypeScript 支持 JSX 传播属性,它在 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 引入了 如果将任何未知的道具传递给 HTML 元素,则发出警告。上面的示例将产生一个 React 运行时警告,说明 textToDisplay
是 <a>
的未知支柱。对于这样的例子,建议的解决方案是使用 对象静止属性对象静止属性提取出您的自定义道具,并使用其余的 JSX 扩展属性:
const {textToDisplay, ...htmlProps} = this.props;
return (
<a {...htmlProps}>{textToDisplay}</a>
);
但是 TypeScript 还不支持这种语法。我知道,希望有一天 我们将能够在 TypeScript 中做到这一点。(< em > 更新: TS 2.1现在支持对象扩展/休息!你怎么还在看这个?与此同时,有什么变通办法吗?我正在寻找一个解决方案,不妥协类型安全,并发现它出奇的困难。例如,我可以这样做:
const customProps = ["textDoDisplay", "otherCustomProp", "etc"];
const htmlProps:HTMLAttributes = Object.assign({}, this.props);
customProps.forEach(prop => delete htmlProps[prop]);
但是,这需要使用字符串属性名,而这些属性名没有针对实际的道具进行验证,因此容易出现输入错误和不良的 IDE 支持。还有更好的办法吗?