如何在样式化组件中使用React DnD? [英] How to use React DnD with styled component?
问题描述
将样式化的组件包装在connectDragSource
中时,出现以下错误:
When wrapping my styled component in connectDragSource
I get the following error:
未捕获的错误:现在只能将本机元素节点传递给React DnD连接器.您可以将PaneItemText__StyledItem包装到
<div>
,或将其本身变成拖动源或放置目标.
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.
此消息的第一个建议是将样式化的组件包装在<div>
中,但这会弄乱我的布局,并且不希望这样做.
我不确定第二个选项的含义-有人能澄清吗?
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);
推荐答案
您应使用样式化组件的 connectDragSource
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)}
/>
)
}
}
您还可以查看我的骑士组件,供官方象棋教程参考. 也可以通过 CodeSandbox .
You can also look at my implementation of Knight component for the official chess tutorial as a reference. It is also accessible through CodeSandbox.
这篇关于如何在样式化组件中使用React DnD?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!