Pie*_*tro 8 javascript reactjs jestjs styled-components
我指的是这个github项目,我正在尝试编写一个KeyPad.js组件的简单测试.
我已经看到在这个问题上打开了问题,一个建议的解决方案是将主题作为prop传递给组件.该解决方案不适用于酶.
在我的情况下,问题是子组件通过ThemeProvider接收主题,并且能够进行测试工作,我需要向所有人添加主题道具.
例:
const tree = renderer.create(
<KeyPad
theme={theme}
cancel={()=> true}
confirm={()=> true}
validation={()=> true}
keyValid={()=>true} />
).toJSON();
expect(tree).toMatchSnapshot();
Run Code Online (Sandbox Code Playgroud)
KeyPad的渲染方法会像这样改变,主题道具无处不在
render() {
let { displayRule, validation, label, confirm, cancel, theme, keyValid, dateFormat } = this.props
return (
<Container theme={theme}>
<Content theme={theme}>
<Header theme={theme}>
<CancelButton theme={theme} onClick={cancel}>
<MdCancel />
</CancelButton>
<Label>{label}</Label>
<ConfirmButton theme={theme} onClick={() => confirm(this.state.input)} disabled={!validation(this.state.input)}>
<MdCheck />
</ConfirmButton>
</Header>
<Display
theme={theme}
value={this.state.input}
displayRule={displayRule}
dateFormat={dateFormat}
cancel={this.cancelLastInsert} />
<Keys>
{[7, 8, 9, 4, 5, 6, 1, 2, 3, '-', 0, '.'].map( key => (
<Button
theme={theme}
key={`button-${key}`}
theme={theme}
click={(key) => this.handleClick(key) }
value={key}
disabled={!keyValid(this.state.input, key, dateFormat)} />
))}
</Keys>
</Content>
</Container>
)
}
Run Code Online (Sandbox Code Playgroud)
我不喜欢这个解决方案.有谁可以帮我这个?
谢谢
Joe*_*kes -1
据我所知,这是完全合理的。库中的每个组件都有一个主题道具,因此您可以像这样设置它。
幸运的是它不使用上下文,否则你会离家更远。为什么不使用上下文: https: //reactjs.org/docs/context.html
如果你不使用 props 来做到这一点,你最终会将组件耦合到另一个外部库。例如:Redux 或 mobx 商店。这意味着它不再是一个真正的组件
尽管它看起来很糟糕。如果你真的想制作一个单独的组件,那么这是一个可行的方法。
归档时间: |
|
查看次数: |
951 次 |
最近记录: |