Storybook: 使用ReactDOM.createPortal方法时发生“目标容器不是DOM元素”错误

创建于 2018-10-29  ·  2评论  ·  资料来源: storybookjs/storybook

描述错误
我想添加一个由ReactDOM.createPortal制作的Modal组件的故事。
模式容器是我在index.html中添加的<div id="modal-root"></div>
但是当我写这样的故事时:

storiesOf('atoms/modal', module)
  .addDecorator(withKnobs)
  .add('Modal', () => (
    <Modal
      isOpen={true}
      onRequestClose={action('onRequestClose')}
    >
      <div>modal</div>
    </Modal>
  ))

发生“目标容器不是DOM元素”错误。

我认为是因为Storybook UI中没有模式根div?
我该如何解决?

重现
往上看

屏幕截图
2018-10-29 15 17 08

代码段
这是我的模态代码的简称:

const modalRoot = document.getElementById('modal-root')

class Modal extends React.Component {
  constructor(props) {
    super(props)
    this.el = document.createElement('div')
  }

  componentDidMount() {
    modalRoot.appendChild(this.el)
  }

  componentWillUnmount() {
    modalRoot.removeChild(this.el)
  }

  handleClickBackDrop = event => {
   this.props.onRequestClose(event)
  }

  render() {
    const { isOpen, children } = this.props

    if (!isOpen) {
      return null
    }

    const modalUI = (
      <BackDropWrapper
        onClick={this.handleClickBackDrop}
      >
        <ModalWrapper>
          {children}
        </ModalWrapper>
      </BackDropWrapper>
    )

    return ReactDOM.createPortal(modalUI, modalRoot)
  }
}

系统:

  • 框架:反应
  • 插件:插件旋钮
  • 版本:4.0.0-alpha.3
react question / support

最有用的评论

由于const modalRoot = document.getElementById('modal-root')是静态调用的,因此需要在导入Modal组件之前生成<div id="modal-root"> 。 我可以建议在加载故事之前在config.js创建此div。

像这样:

// config.js
const modalRoot = document.createElement('div');
modalRoot.setAttribute('id', 'modal-root');
document.body.append(modalRoot);

所有2条评论

由于const modalRoot = document.getElementById('modal-root')是静态调用的,因此需要在导入Modal组件之前生成<div id="modal-root"> 。 我可以建议在加载故事之前在config.js创建此div。

像这样:

// config.js
const modalRoot = document.createElement('div');
modalRoot.setAttribute('id', 'modal-root');
document.body.append(modalRoot);

@ igor-dv谢谢您的建议有效。

此页面是否有帮助?
0 / 5 - 0 等级