如何嵌套两个自定义Storybook装饰器以创建新装饰器?
组合两个装饰器的实现方案
你可以通过嵌套调用两个装饰器来创建一个组合后的装饰器,本质是让一个装饰器的逻辑包裹另一个装饰器的执行流程。以下是具体实现:
原始装饰器代码
const withDecorator1 = (story, options) => { // do something with the options return <>{story()}</>; }; const withDecorator2 = (story, options) => { // do something with the options return <>{story()}</>; };
组合后的装饰器
const withCombinedDecorator = (story, options) => { // 先应用withDecorator1逻辑,再在其内部执行withDecorator2 return withDecorator1(() => withDecorator2(story, options), options); };
如果需要调整执行顺序,让withDecorator2先执行逻辑,再执行withDecorator1,可以修改嵌套顺序:
const withCombinedDecorator = (story, options) => { return withDecorator2(() => withDecorator1(story, options), options); };
逻辑说明
- 组合装饰器接收
story和options参数后,外层装饰器会把内层装饰器的执行结果作为新的story传入 - 两个装饰器都能正常获取到传入的
options,各自执行内部逻辑 - 最终渲染的是经过两层装饰器处理后的故事内容
内容的提问来源于stack exchange,提问作者Mutai Mwiti
相关产品推荐
相关产品推荐

