styled-components 和 react-redux connect, withTheme HOC 可以一起使用,而不需要这种糟糕的解决方法吗?

jth*_*eis 5 reactjs redux react-redux styled-components

我们正在尝试将代码库从 styled-components v3 升级到 v4/5。我们使用的模式似乎不再有效,尽管它看起来应该有效。

模式(伪代码):

// In reusable component file

const LeafComponent = (props) => whatever
const StyledLeafComponent = styled(LeafComponent)` styles which might reference connect props here `
const ReusableComponent = connectOrWithTheme(StyledLeafComponent)

// In some other file where the reusable component is being customized

const CustomizedComponent = styled(ReusableComponent)` additional context-specific styles here `
Run Code Online (Sandbox Code Playgroud)

在 v4 和 v5 中,此模式对于 connect() 和 withTheme 都失败,相应的道具(商店道具或主题)在可重用组件中未定义(来自 connect() 的道具在叶组件的样式中也未定义,我们可能需要引用它们)。事实上,connect() 中的mapStateToProps 似乎根本没有运行!

以下解决方法仅在其间添加一个传递组件似乎可以解决问题:

const CustomizedComponent = styled(props => <ReusableComponent {...props} />)` additional context-specific styles here `
Run Code Online (Sandbox Code Playgroud)

但这种解决方法的问题在于,很容易意外地忽略并引入偷偷摸摸的运行时错误,更不用说我们正在升级的代码库会成为可能出现运行时错误的雷区,直到我们对样式组件的每次使用进行彻底审查,我们有 connect、withTheme,可能还有其他类似的 HOC(很多)。(我们使用的是 TypeScript,因此编译器错误很有价值)。

显然,最好的解决方案是在样式组件本身中修复此问题,但目前看来不太可能。我们花了几个月的时间试图得到比这更好的答案,在 GitHub 上针对样式组件存储库提出了问题,并在 Spectrum 上进行了联系。我们在codesandbox上简单清晰地重现了该问题:

没有回应。

有比上面更好的解决方法吗?或者这就是我们所坚持的?我们一开始使用这种模式是否就被误导了,应该采取其他措施?当然,styled-components、react 和 redux 都是流行的库,并且被许多人一起使用。这个问题以前肯定遇到过并解决过。