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

时间:2021-02-22 09:47:33

标签: reactjs material-ui react-beautiful-dnd

我使用 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>

1 个答案:

答案 0 :(得分:0)

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-