正如@hamms所指出的,这是一种反模式。有
better ways to implement themes in React
使用普通的旧CSS。
这么说吧,这里有一个你的用例的工作示例-
https://codesandbox.io/s/ymqwyww22z
.
基本上,我所做的是:
-
制造
List
基于类的组件。把一个功能组件包装成一个并不太麻烦。
import React, { Component } from "react";
export default class List extends Component {
render() {
return (
<ul>
<li>1</li>
<li>2</li>
</ul>
);
}
}
-
实施
render
在动态类中
Red<Component>
首先获取从基本组件的呈现返回的元素树,然后对其进行编辑。
import React from "react";
export default function makeRed(Component) {
return class RedComponent extends Component {
constructor(props) {
super(props);
RedComponent.displayName = `Red${Component.name}`;
}
render() {
let componentElement = super.render();
let { children, ...rest } = componentElement.props;
children = React.Children.map(children, child => {
return React.cloneElement(child, {
...child.props,
style: {
backgroundColor: "red"
}
});
});
return React.cloneElement(componentElement, rest, ...children);
}
};
}
这和
createElement
版本
makeRed
?
作为
变红
返回HOC,当您在
App
组件,你不给它分配道具。像这样的。。。
function App() {
return <RedList />; // no props!
}
所以在动态组件函数中,使用
createElement公司
要创建新实例,
component.props
不要带孩子。自从
列表
创建自己的子级,您需要获取并修改它们,而不是从
props
.