How to use React DnD with styled component?

2019-06-08 13:38发布

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);

2条回答
Rolldiameter
2楼-- · 2019-06-08 14:28

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

查看更多
我命由我不由天
3楼-- · 2019-06-08 14:33

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.

查看更多
登录 后发表回答