覆盖触发器在自定义组件上无法使用

10

当鼠标悬停在自定义组件(按钮)上时,我想显示一个弹出框:

class MyComponent extends React.PureComponent<MyComponentProperties>  {
    public render(): JSX.Element {
        const overlay: JSX.Element = (
            <Popover id={this.uuid}>
                <Popover.Content>
                    Hello world!
                </Popover.Content>
            </Popover>
        );

        return <OverlayTrigger trigger="hover" placement="auto" delay={{show : 700, hide : 0}} overlay={overlay}>
            <MyFancyButton ... />
        </OverlayTrigger >
    }
}

class MyFancyButton extends React.PureComponent<MyFancyButtonProperties> {
    public render(): JSX.Element {
        return <button ...>Hover me!</button>
    }
}

弹出框没有显示。但是,如果我将MyComponentrender函数的返回值更改为以下内容,则它可以正常工作:

return <OverlayTrigger trigger="hover" placement="auto" delay={{show : 700, hide : 0}} overlay={overlay}>
    <button>Hover me!</button>
</OverlayTrigger >

我检查了https://react-bootstrap.github.io/components/overlays/#overlay-trigger,它说:
请注意,触发组件必须能够接受ref,因为Overlay将尝试添加一个。对于函数组件,您可以使用forwardRef()。
我不确定如何实现这一点。我尝试在MyFancyButtonProperties中添加一个ref属性,并将其转发到button,但它不起作用:
class MyFancyButton extends React.PureComponent<MyFancyButtonProperties> {
    public render(): JSX.Element {
        return <button ref={this.props.ref} ...>Hover me!</button>
    }
}

我的版本:

  • React 16.8.6
  • React Bootstrap 1.0.0-beta.14

我曾经问过一个类似的问题,想知道为什么forwardRef在使用bootstrap时似乎无法正常工作:https://stackoverflow.com/questions/60875068/react-forwardref-does-not-seem-to-work-with-bootstrap-overlay - amaster
2个回答

19

4
这在我的情况下破坏了放置位置。 - Geoffrey Hale

2

您的自定义组件需要通过事件处理程序传递props。

const FancyButton = ({ children, ...props }) => (
  <Button {...props}>
    {children}
  </Button>
);

来源: https://github.com/react-bootstrap/react-bootstrap/issues/2208

这个问题与React-Bootstrap的版本升级有关。更新了版本后,很可能会遇到各种错误,但这是正常的。解决此类问题的最佳方法是手动更改代码并在文档中查找所需的更改。另外,确保您已经仔细阅读了文档以及您正在使用的React-Bootstrap版本的兼容性信息。


这可以在不添加额外的span的情况下控制DOM。 - efreed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接