【发布时间】:2021-07-30 17:03:15
【问题描述】:
我有一个类似的组件
import React, { ReactNode } from "react";
const defaultContainerProps = {
heading: <h1>Default Heading</h1>,
};
function App({
children,
heading,
}: {
children: ReactNode;
} & typeof defaultContainerProps) {
return (
<div>
<h1>{heading}</h1>
{children}
</div>
);
}
App.defaultProps = defaultContainerProps;
export default App;
它工作得很好,但是在 es6 中可以直接在函数参数中给出默认道具,所以我像这样更新了我的函数
const defaultContainerProps = {
heading: <h1>Default Heading</h1>,
};
function App({
children,
heading = defaultContainerProps.heading,
}: {
children: ReactNode;
} & typeof defaultContainerProps) {
return (
<div>
<h1>{heading}</h1>
{children}
</div>
);
}
但是当我使用这个组件时,它希望我给标题道具 错误:'{ children: string; 类型中缺少属性 'heading' }' 但在类型 '{ 标题:JSX.Element; 中是必需的; }'。
使用该组件的主文件
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
ReactDOM.render(
<React.StrictMode>
<App>Foo</App> // Property 'heading' is missing in type '{ children: string; }' but required in type '{ heading: JSX.Element; }'.
</React.StrictMode>,
document.getElementById("root")
);
【问题讨论】:
标签: reactjs typescript