【问题标题】:How to implement Drag and Drop in Class based Component in react-dnd如何在 react-dnd 中实现基于类的组件中的拖放
【发布时间】:2020-05-06 20:43:23
【问题描述】:

我是新来的反应并尝试使用 react-dnd 实现拖放。但是我不能在基于类的组件中使用钩子。由于以下代码部分,我收到错误消息。

 const [{ isDragging }, drag] = useDrag({
           item: { type: ItemTypes.Student },
          collect: (monitor) => ({
            isDragging: !!monitor.isDragging(),
          }),
        });

如何在仍然使用基于类的组件的同时实现相同的功能? 以下是完整代码

class App extends Component {
  state = {
    values: [],
  };
const [{ isDragging }, drag] = useDrag({
      item: { type: ItemTypes.Student },
      collect: (monitor) => ({
        isDragging: !!monitor.isDragging(),
      }),
    });

  divStyle = {
    "margin-left": "20px",
  };

  componentDidMount() {
    axios.get("http://localhost:5000/api/student").then((response) => {
      this.setState({
        values: response.data,
      });
    });
  }

  render() {

    return (
      <div
        ref={drag}
        style={{
          opacity: isDragging ? 0.5 : 1,
          fontSize: 25,
          fontWeight: "bold",
          cursor: "move",
        }}
      >
        <Header as="h2">
          <Icon name="users" />
          <Header.Content>Reactivities</Header.Content>
        </Header>

        {this.state.values.map((student: any) => (
          <DndProvider backend={Backend}>
            <List key={student.id} relaxed>
              <List.Item>
                <Image
                  style={this.divStyle}
                  avatar
                  src="https://react.semantic-ui.com/images/avatar/small/daniel.jpg"
                />
                <List.Content>
                  <List.Header as="a">
                    {student.firstName} {student.lastName}
                  </List.Header>
                  <List.Description></List.Description>
                </List.Content>
              </List.Item>
            </List>
          </DndProvider>
          //  <List.Item key={value.id}>{value.name}</List.Item>
        ))}
      </div>
    );
  }
}

export default App;

【问题讨论】:

    标签: reactjs react-dnd


    【解决方案1】:

    您不能在类组件中使用钩子,如下所述: https://reactjs.org/docs/hooks-faq.html#should-i-use-hooks-classes-or-a-mix-of-both

    你不能在类组件中使用 Hooks,但你绝对可以将类和函数组件与 Hooks 混合在一个树中。组件是使用 Hooks 的类还是函数是该组件的实现细节。从长远来看,我们希望 Hooks 成为人们编写 React 组件的主要方式。

    因此,如果你想使用这个库,你需要将你的组件重构为一个函数组件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-17
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 2023-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多