英文:
How to preview a React Portal component using storybook
问题
我有这段代码:
index.html
...
<body>
<div id="example-root"></div>
</body>
...
Component.tsx
...
const exampleRoot = document.getElementById("example-root")
function Component() {
return ReactDOM.createPortal(<div>...</div>, exampleRoot)
}
Stories.tsx
...
const ExampleStory = () => (
<>
<div id="example-root"></div>
<Component />
</>
)
我需要在storybook中渲染<Component/>
,但问题是<Component/>
需要找到#example-root
元素进行渲染,但当我运行storybook时它无法找到这个根元素,无法渲染,但在普通页面上运行相同的代码时它正常工作,除了storybook之外,所以问题出在storybook上。
我认为这是因为<Component/>
在storybook之前挂载,所以组件无法找到#example-root
元素。有趣的是,在所有东西都被渲染完成之后(组件和storybook),如果我对<Component/>
的代码进行任何更改并保存,然后它就可以工作!<Component/>
找到了根元素并被渲染。
那么,我该如何解决这个问题?
英文:
I have this code:
index.html
...
<body>
<div id="example-root"></div>
</body>
...
Component.tsx
...
const exampleRoot = document.getElementById("example-root")
function Component() {
return ReactDOM.createPortal(<div>...</div>, exampleRoot)
}
Stories.tsx
...
const ExampleStory = () => (
<>
<div id="example-root"></div>
<Component />
</>
)
I need to render <Component/>
on storybook, but the problem is that <Component/>
needs to find
the #example-root
element to be rendered, but when I run the storybook it's unable to find this root element and it can't be rendered, but when I run the same code at normal page it works fine, except in storybook, so the problem is on storybook.
I think it's happening because the <Component />
is mounted before the storybook, so the the component can't find the #example-root
element. A funny thing is that after everything has been rendered(component & storybook) if I do any change at <Component />
code and save it, then it works! The <Component />
find the root and is rendered.
So, how do I solve this?
答案1
得分: 1
我找到了关于这个问题的答案
如果你需要渲染一个 React Portal 组件,前往你的工作区中的 .storybook 文件夹,然后创建一个名为 preview-body.html 的新文件,在这个文件中,你只需要创建 portal 的根标签,例如:
// .storybook > preview-body.html
<div id="example-root"></div>
现在你的 React Portal 组件已经准备好在你的故事中渲染了。
英文:
I found the answer for this
If you need to render a component that is a React Portal, go to .storybook folder in your workspace, and then create a new file called preview-body.html, inside this file you just need to create the portal root tag, for example:
// .storybook > preview-body.html
<div id="example-root"></div>
Now your React Portal component is ready to be rendered in your story.
答案2
得分: 0
可以通过在模板上添加<div id="portal"/>来渲染它,但仅在控件更改时才有效。
英文:
it could be render by adding <div id ="portal" /> on Template, but it works only when the controls are changed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论