您好,我有一个问题,我的自定义拖动层同时使用我的自定义和 HTML 定义的样式进行渲染。 同时我被警告“在更新转换期间不能调用 setState”。
这是我的代码:
import React from 'react';
import PropTypes from 'prop-types';
import { DragLayer } from 'react-dnd';
import ItemDragPreview from './ItemDragPreview';
const layerStyles = {
position: 'fixed',
pointerEvents: 'none',
zIndex: 200000
};
function getItemStyles(props){
const {initialOffset, currentOffset} = props;
if (!initialOffset || !currentOffset) {
return {
display: 'none'
};
}
let {x,y} = currentOffset;
const transform = `translate(${x}px,${y}px)`;
return{
transform
};
}
class CustomDragLayer extends React.Component{
static propTypes = {
item: PropTypes.object,
itemType: PropTypes.string,
initialOffset: PropTypes.shape({
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired
}),
currentOffset: PropTypes.shape({
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired
}),
isDragging: PropTypes.bool.isRequired,
}
renderItem(type,item){
return (<ItemDragPreview ruleitem={item}/>);
}
render(){
const {item,itemType,isDragging} = this.props;
if(!isDragging){
return null;
}
return (
<div style={layerStyles}>
<div style={getItemStyles(this.props)}>
{this.renderItem(itemType,item)}
</div>
</div>
);
}
}
let collect = monitor =>{
return {
item: monitor.getItem(),
itemType: monitor.getItemType(),
currentOffset: monitor.getSourceClientOffset(),
initialOffset: monitor.getInitialSourceClientOffset(),
isDragging: monitor.isDragging()
};
}
export default DragLayer(collect)(CustomDragLayer);
这是警告:
警告:setState(...):在现有状态转换期间无法更新(例如在
render
或其他组件的构造函数中)。 渲染方法应该是 props 和 state 的纯函数; 构造函数副作用是一种反模式,但可以移至componentWillMount
。
我想知道这是我的错误还是图书馆的错误。
谢谢!
ItemDragPreview 的代码是什么样的? 我在尝试渲染 DragSource 组件时遇到了这个问题。
确保 ItemDragPreview 也不是 DragSource。 如果您在 ItemDragPreview 中管理状态,请尝试禁用它。 除了该组件中的 html/jsx 之外,基本上将所有内容都剃掉。 从那张白纸开始,然后一一添加。
原来我也必须更改连接器中的拖动预览。 现在一切都好
我也有这个问题,你是什么意思“在连接器中”?
最有用的评论
ItemDragPreview 的代码是什么样的? 我在尝试渲染 DragSource 组件时遇到了这个问题。
确保 ItemDragPreview 也不是 DragSource。 如果您在 ItemDragPreview 中管理状态,请尝试禁用它。 除了该组件中的 html/jsx 之外,基本上将所有内容都剃掉。 从那张白纸开始,然后一一添加。