【问题标题】:React | Gatsby: Components inside or outside main page component反应 | Gatsby:主页组件内部或外部的组件
【发布时间】:2020-04-25 21:48:22
【问题描述】:

在学习如何使用 react-beautiful-dnd 库时,我发现(在构建库所需的结构时)如果我在主应用程序之外定义组件,它适用于 React,但不适用于 Gatsby (开发),它开始工作,但随后出现错误

但如果我在主应用程序中移动这些组件,那么它也适用于 Gatsby

示例代码:

export default () => {
  const [elements, setElements] = useState(myElements)

  const onDragEnd = result => {
    const { destination, source} = result

    if (!destination) return
    if (destination.droppableId === source.droppableId && destination.index === source.index) return

    const new_elements = reorder(elements, source.droppableId, destination.droppableId, source.index, destination.index)
    setElements(new_elements)
  }

  const Columns = ({ arr }) =>
    arr.map((col, i) => (
      <Droppable droppableId={col.columnId} key={i}>
        {(provided, snapshot) => (
          <Ul ref={provided.innerRef}>
            <Elements arr={col.items} />
            {provided.placeholder}
          </Ul>
        )}
      </Droppable>
    ))

  const Elements = ({ arr }) =>
    arr.map((el, j) => (
      <Draggable draggableId={el.id} index={j} key={j}>
        {(provided, snapshot) => (
          <Li ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps}>
            {el.text}
          </Li>
        )}
      </Draggable>
    ))

  return (
    <DragDropContext onDragEnd={onDragEnd}>
      <Grid>
        <Columns arr={myElements} />
      </Grid>
    </DragDropContext>
  )
}

所以如果 ColumnsElements 在外部定义,它就不起作用(但它适用于 React)

为什么会这样?

(沙盒:https://codesandbox.io/s/using-react-beautiful-dnd-with-hooks-bfwzl?fontsize=14&hidenavigation=1&theme=dark

【问题讨论】:

  • 你在 gatsby 中遇到的错误是什么?
  • Unable to find draggable with id: ,

标签: javascript reactjs gatsby react-beautiful-dnd


【解决方案1】:

如文档中所述https://github.com/atlassian/react-beautiful-dnd/blob/master/docs/api/draggable.md#keys-for-a-list-of-draggable-

Your key should not include the index of the item

更改后,它会按预期工作

  <Droppable droppableId={col.columnId} key={col.columnId}>
  <Draggable draggableId={el.id} index={j} key={el.id}>

【讨论】:

    猜你喜欢
    • 2020-03-07
    • 2020-01-25
    • 1970-01-01
    • 2017-08-24
    • 2021-03-03
    • 2016-01-13
    • 2016-07-31
    • 2017-07-06
    • 2018-06-03
    相关资源
    最近更新 更多