错误无法读取带有样式组件的React语义UI弹出窗口中未定义的属性'left'

问题描述 投票:2回答:1

我有一个样式化的组件,例如:

import styled from 'styled-components';
const TagIcon = styled(Icon).attrs({
  name: 'tag',
})`
  cursor: pointer;
  font-size: 14px !important;
`

如果我在语义用户界面反应的布局中使用它,则在大多数情况下都可以正常工作。但是,如果我将其用作SUI Popup组件的触发器,则会导致崩溃:

<Popup content="Test Popup" trigger={<TagIcon />} />
Load Page = ... Unhandled Rejection (TypeError): Cannot read property 'left' of undefined
getBoundingClientRect
src/utils/getBoundingClientRect.js:38
  35 | catch(e){}
  36 | 
  37 | const result = {
> 38 |   left: rect.left,
     | ^  39 |   top: rect.top,
  40 |   width: rect.right - rect.left,
  41 |   height: rect.bottom - rect.top,
...
Popper.update$$1
src/index.js:94
  91 | // We can't use class properties because they don't get listed in the
  92 | // class prototype and break stuff like Sinon stubs
  93 | update() {
> 94 |   return update.call(this);
     | ^  95 | }
  96 | destroy() {
  97 |   return destroy.call(this);

如果我将“ TagIcon”样式的组件替换为等效的(ish)组件,它将正常工作:

<Popup content="Test Popup" trigger={<Icon name="tag">} />

有人遇到这个问题并有解决方案吗?我不确定如果有问题会在哪个git项目中进行报告,因为似乎在样式化组件和语义UI-react(或语义UI)之间,事情的处理方式可能存在冲突。 )。

reactjs semantic-ui styled-components semantic-ui-react
1个回答
0
投票

我也遇到了同样的问题,并调试了几个小时,最终发现它实际上很容易解决!问题是由于某种原因popper.js无法接收DOM ref来计算left / top / width / height,因此您需要使用forwardRef和ref“手动”传递它,例如:

// Your Icon component 
const Icon = forwardRef(
  (props, ref) => (
    <img
      src={props.url}
      ref={ref}
    />
  )
);

之后,请正常使用它:

const TagIcon = styled(Icon)`
  width: 40px;
`

<Popup content="Test Popup" trigger={<TagIcon url="https://test-image.com">} />

我希望它可以帮助某人!

© www.soinside.com 2019 - 2024. All rights reserved.