How to use React DnD with styled component?

你说的曾经没有我的故事 提交于 2019-12-23 03:15:49

问题


When wrapping my styled component in connectDragSource I get the following error:

Uncaught Error: Only native element nodes can now be passed to React DnD connectors.You can either wrap PaneItemText__StyledItem into a <div>, or turn it into a drag source or a drop target itself.

The first suggestion from this message is to wrap my styled component in a <div>, but this will mess with my layout and would prefer not to do this. I'm not sure what the second option is suggesting - would anybody be able to clarify?

Below is an rough example what I am doing:

import React, { Component } from 'react';
import styled from 'styled-components';
import { DragSource } from 'react-dnd';

const StyledComponent = syled.div`
...
`;

class MyComponent extends Component {
    ...
    render() {
        const { connectDragSource } = this.props;
        return connectDragSource(<StyledComponent />)
    }
}

const itemSource = {
    beginDrag(props) {
        /* code here */
    },
    endDrag(props) {
        /* code here */
    }
};

function collect(connect, monitor) {
    return {
        connectDragSource: connect.dragSource(),
        isDragging: monitor.isDragging()
    }
}

export default DragSource('foo', itemSource, collect(MyComponent);

回答1:


You should use Styled Component's innerRef to get the underlying DOM node, then you can call your connectDragSource to it.

In your case, it should be like this:

class MyComponent extends Component {
...
    render() {
        const { connectDragSource } = this.props;
        return (
            <StyledComponent
                innerRef={instance => connectDragSource(instance)}
            />
        )
    }
}

You can also look at my implementation of Knight component for the official chess tutorial as a reference. It is also accessible through CodeSandbox.




回答2:


If you are using multiple connectors you can do the following:

<MyStyledComponent
  innerRef={instance => {
    connectDragSource(instance);
    connectDropTarget(instance);
  }}
/>

Source: https://github.com/react-dnd/react-dnd/issues/347#issuecomment-221703726



来源:https://stackoverflow.com/questions/50220622/how-to-use-react-dnd-with-styled-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!