首页 > 解决方案 > 函数组件不能被赋予 refs。尝试访问此 ref 将失败

问题描述

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

错误:在此处输入图像描述

代码:

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>

标签: reactjsmaterial-uireact-beautiful-dnd

解决方案


用于HTML DOM元素并用于refReact组件innerRef

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

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


推荐阅读