反应 | Gatsby:主页组件内部或外部的组件
React | Gatsby: Components inside or outside main page component
在学习如何使用 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>
)
}
因此,如果 Columns
和 Elements
是在外部定义的,则它不起作用(但它与 React 一起使用)
为什么会这样?
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}>
在学习如何使用 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>
)
}
因此,如果 Columns
和 Elements
是在外部定义的,则它不起作用(但它与 React 一起使用)
为什么会这样?
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}>