我无法弄清楚如何使用Typescript为我的组件设置默认属性值.
这是源代码:
class PageState
{
}
export class PageProps
{
foo: string = "bar";
}
export class PageComponent extends React.Component<PageProps, PageState>
{
public render(): JSX.Element
{
return (
<span>Hello, world</span>
);
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用这样的组件时:
ReactDOM.render(<PageComponent />, document.getElementById("page"));
Run Code Online (Sandbox Code Playgroud)
我得到一个错误,说财产foo缺失.我想使用默认值.我也尝试static defaultProps = ...在组件内部使用,但它没有像我怀疑的那样有效.
src/typescript/main.tsx(8,17): error TS2324: Property 'foo' is missing in type 'IntrinsicAttributes & IntrinsicClassAttributes<PageComponent> & PageProps & { children?: ReactEle...'.
Run Code Online (Sandbox Code Playgroud)
我如何使用默认属性值?我公司使用的许多JS组件都依赖于它们而不使用它们不是一种选择.
我的 Webpack 有问题。它正确地编译和树摇动,但给了我数百个错误,因为由于某种原因它对 node_modules 中的类型定义做了一些事情,即使它不应该这样做,因为在我的入口点中不需要/导入任何模块。
我的 webpack.config.js:
const ForkCheckerPlugin = require("awesome-typescript-loader").ForkCheckerPlugin;
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const webpack = require("webpack");
module.exports = {
entry:
{
browser: __dirname + "/source/index.tsx"
},
module:
{
loaders:
[
{ test: /(\.ts|\.tsx)$/, loader: "awesome-typescript-loader" },
{ test: /\.css$/, loader: ExtractTextPlugin.extract({ loader: "css-loader?modules" }) },
{ test: /\.png$/, loader: "url-loader" },
{ test: /\.jpg$/, loader: "url-loader" },
{ test: /\.json$/, loader: "json-loader" },
]
},
plugins:
[
new webpack.DefinePlugin({ "process.env": { NODE_ENV: JSON.stringify("production") } }),
new webpack.optimize.DedupePlugin(), …Run Code Online (Sandbox Code Playgroud)