使用React.Children.map时,我试图访问孩子的displayName。 Typescript似乎无法识别type
上的child
属性。但是,当我只是console.log
child
时,我可以看到它具有type
属性。
我一直在参考this教程来创建复合组件。以下是我要实现的(因此目前无法正常工作):
<Card>
<Card.Title>Title</Card.Title>
<Card.Subtitle>Subtitle</Card.Subtitle>
<Card.Body>Body</Card.Body>
<Card.Footer>Footer</Card.Footer>
<Card.Image src="assets/images/logo.png" />
</Card>
这是我目前在Card
组件中所拥有的
import * as React from "react";
import { connect } from "react-redux";
import { ITheme } from "src/modules/CSS";
interface IState {
theme: ITheme;
}
interface IProps extends IState {
children: React.ReactNode;
}
const { Provider, Consumer } = React.createContext<IState | null>(null);
const Title = ({ children }: IProps) => (
<Consumer>{() => <div>{children}</div>}</Consumer>
);
Title.displayName = "Title";
class Card extends React.Component<IProps> {
constructor(props: IProps) {
super(props);
}
public render() {
const { children } = this.props;
return (
<Provider value={{ theme: this.props.theme }}>
{React.Children.map(children, (child) => {
if (child) {
console.log(child.type.displayName); /* Property 'type' does not exist on type 'string | number | true | {} | ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)> | ReactNodeArray | ReactPortal' */
}
return child;
})}
</Provider>
);
}
}
const mapStateToProps = ({ theme }: IStoreState): IState => ({
theme,
});
export default connect(mapStateToProps)(Card);
编辑:这是我的tsconfig
和tslint
,以防可能影响我的问题:
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"allowJs": true,
"jsx": "react",
"sourceMap": true,
"outDir": "./dist/",
"removeComments": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "node",
"baseUrl": ".",
"resolveJsonModule": true,
"paths": {
"*": ["*", "types/*"]
},
"esModuleInterop": true
},
"exclude": ["node_modules", "**/*.spec.ts"]
}
tslint.json
{
"defaultSeverity": "error",
"extends": ["tslint:recommended"],
"jsRules": {},
"rules": {
"arrow-return-shorthand": [true, "multiline"],
"object-literal-sort-keys": false,
"no-console": false
},
"rulesDirectory": []
}