gpt4 book ai didi

javascript - React - 发送 ref 作为 Prop 不起作用

转载 作者:行者123 更新时间:2023-11-29 20:35:04 25 4
gpt4 key购买 nike

我正在使用 react-mui我的项目中的库,我想在其中实现一个 MenuList 组件,在 MenuList composition here 下找到.在我的应用程序中,虽然我将 ref 作为 prop 向下发送到一个 child component,我有一个 menu。你可以看到codesandbox例子here .当我从这样的父组件发送 refsetRef 方法作为 props 时:

state = {
open: false,
ref: React.createRef()
};

setRef = element => {
this.setState({ ref: element });
};

handleToggle = () => {
this.setState(state => ({ open: !state.open }));
};

handleClose = () => {
this.setState({ open: false });
};

render() {
return (
<MenuListComposition
setRef={this.setRef}
handleToggle={this.handleToggle}
handleClose={this.handleClose}
open={this.state.open}
ref={this.state.ref}
/>
);
}

对于具有菜单按钮的子组件:

    <MenuButton
className={classes.button}
handleToggle={handleToggle}
setRef={setRef}
open={open}
ref={ref}
/>

然后具有菜单列表的 Popper 组件在错误的位置打开,如果您单击 TOGGLE MENU GROW 按钮,您可以在 codesanbox 示例中看到这一点。

      <Popper open={open} anchorEl={ref} transition disablePortal>
{({ TransitionProps, placement }) => (
<Grow
{...TransitionProps}
id="menu-list-grow"
style={{
transformOrigin:
placement === "bottom" ? "center top" : "center bottom"
}}
>
<Paper>
<ClickAwayListener onClickAway={handleClose}>
<MenuList>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<MenuItem onClick={handleClose}>Logout</MenuItem>
</MenuList>
</ClickAwayListener>
</Paper>
</Grow>
)}
</Popper>

我做错了什么以及如何解决这个问题,或者我如何在 stateless 组件中使用 ref 以避免向下发送 ref 作为 prop?

最佳答案

ref 是 reactjs 中的关键字。当您使用 ref 作为 Prop 时,它会将组件链接到 ref 对象。在 FancyButton 组件和 MenuListComposition 组件上将其重命名为您喜欢的名称。

来自 react documentation.

React supports a special attribute that you can attach to any component.

Working example ref 在两个组件中都重命名为 parentRef。

编辑:

正如 Vaibhav Shukla 所指出的,您可以在 FancyButtonMenuListComposition 上使用 React.forwardRef,这可能是正确的方法这样做。

Working example

关于javascript - React - 发送 ref 作为 Prop 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56947196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com