不能给函数组件提供 refs尝试访问此引用将失败

问题描述

我使用 lib react-beautiful-dnd,但在尝试在 MenuItem 组件中传递引用时出现错误。我用 React.forwardRef 做了一个 HOC,但没有帮助。如果有人知道如何解决问题,我将不胜感激。

错误

enter image description here

代码

const RefMenuItem = React.forwardRef((props,ref) => (
    <MenuItem
        onClick = {props.onClick}
        ref     = {ref}
        {...props.provided.dragHandleProps}
        {...props.provided.draggableProps}
    >
        {props.children}
    </MenuItem>
));

export default function DraggableItem({ item,index,onClick }) {
    // const classes = useStyles();
    return (
        <Draggable draggableId={item.id} index={index}>
            {provided => (<RefMenuItem
                onClick  = {onClick}
                ref      = {provided.innerRef}
                provided = {provided}
            >
                <DragIndicatorIcon />
                {item.name}
                <CreateIcon />
            </RefMenuItem>)}
        </Draggable>
    );
}

<Select
    variant   = 'outlined'
    value     = {selectedValue}
    className = {selectClasses}
>
    <DragDropContext onDragEnd={onDragEnd}>
        <Droppable droppableId='list'>
            {provided => (<div ref = {provided.innerRef} {...provided.droppableProps}>
                {state.items.map((item,index) => (
                    <DraggableItem
                        item    = {item}
                        index   = {index}
                        key     = {item.id}
                        onClick = {handleAudienceChange}
                    />
                ))}
                {provided.placeholder}
            </div>)}
        </Droppable>
    </DragDropContext>
</Select>

解决方法

HTML DOM 元素使用 ref,对 React 组件使用 innerRef

<MenuItem
  innerRef={provided.innerRef}
  ...
/>

https://github.com/atlassian/react-beautiful-dnd/blob/master/docs/guides/using-inner-ref.md#a-common-error-

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...