3

我一直在关注 Egghead 的官方课程(https://egghead.io/lessons/react-reorder-a-list-with-react-beautiful-dnd和示例工作代码:https ://codesandbox.io/s /52p60qqlpp)并写道:

https://codesandbox.io/s/00k3rwq3qn

但是,它实际上并没有拖放。我查看了几个示例,但无法在我的代码中发现问题。我非常感谢有人反馈我的错误是什么。

谢谢

4

3 回答 3

5

我认为使用内联样式Draggable在 in中效果不佳react-beautiful-dnd。如果您想将样式应用到Task您应该使用的组件,如果您删除内联样式配置https://codesandbox.io/s/6lq0854m6rstyled-components,此示例将显示它可以正常工作。

而是使用样式组件

import React from "react";
import styled from "styled-components";
import { Draggable } from "react-beautiful-dnd";

const Container = styled.div`
  margin: 10px;
  border: 1px solid black;
`;

export default class Task extends React.Component {
  render() {
    return (
      <Draggable draggableId={this.props.task.id} index={this.props.index}>
        {(provided, snapshot) => (
          <Container
            {...provided.draggableProps}
            {...provided.dragHandleProps}
            ref={provided.innerRef}
          >
            {this.props.task.content}
          </Container>
        )}
      </Draggable>
    );
  }
}

编辑: 似乎您可以将内联样式应用于可拖动,但是您应该DraggableProps.stylesDraggable组件的子函数内扩展,请参见此处

{(provided, snapshot) => (
    const style = {
        margin: "10px",
        border: "1px solid black",
        ...provided.draggableProps.style,
    };
    return <div
        {...provided.draggableProps}
        {...provided.dragHandleProps}
        ref={provided.innerRef}
        style={style}
        >
        {this.props.task.content}
    </div>
)}
于 2019-03-21T21:09:56.833 回答
1

@Ian 的回答对我来说效果不佳。所以我检查了react-beautiful-dnd's 的文档并想出了另一种解决方法来解决这个问题:

const styles = {
  backgroundImage: `url(${background.MEDIUM})`,
  backgroundSize: 'cover',
};

...

  {(provided) => {
    const otherProps = {
      ...provided.draggableProps,
      style: {
        ...provided.draggableProps.style,
        ...styles,
      },
    };
    return (<div
        {...otherProps}
        {...provided.dragHandleProps}
        ref={provided.innerRef}
        >
        {this.props.task.content}
    </div>)
  }}
于 2020-02-12T12:25:20.063 回答
0

如果您尝试使用官方文档而不是使用 styled-components 库使用 React 功能组件构建可拖动列表,那么它需要工作。它会给你一些错误。因此,使用 className 属性应用样式,然后错误就会消失,代码也将开始工作。

于 2021-05-11T15:12:10.413 回答