我正在尝试动态设置 displayName,因为每个组件都呈现为 <Component ... />
并使其无法调试。到目前为止我已经设置了static displayName
在每个组件上都运行良好,只是有很多重复的代码。
许多组件扩展了该组件,因此导致完全由未命名组件组成的层次结构。我怎样才能保存设置static displayName
在扩展 Component 的每个组件上?
根组件
export class Component extends React.Component {
static component = 'span';
static style = {
base: {}
};
constructor() {
super(...arguments);
this.style = this.constructor.style;
this.switches = this.constructor.switches;
this.component = this.constructor.component;
// this.displayName = this.constructor.displayName;
}
getRenderProps() {
...
return props;
}
render() {
return React.createElement(this.component, this.getRenderProps(), this.props.children);
}
}
其他类
class SomeClass extends Component {
...
}
SomeClass 现在呈现为 <Component>
除非明确设置 static displayName
其结果是:
最佳答案
const decorate = <P extends object>(
Component: React.ComponentType<P>,
displayName?:string
): React.FC<P> => ({
...props
}: P) =>{
const WithName = withStyles({})(Component as React.FC)
WithName.displayName = displayName
return <WithName {...props as P} />
}
然后像这样使用:
(注意!需要在组件之外)
const MyComp = decorate(Compo, "MyComp")
如果有人找到了更简洁的方式,请标记我的名字
关于javascript - 如何使用更高阶的组件动态设置 displayName ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38938095/