์๋ ํ์ธ์, ์ฌ์ฉ์ ์ ์ ๋๋๊ทธ ๋ ์ด์ด๊ฐ ์ฌ์ฉ์ ์ ์ ๋ฐ 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๋ฅผ ์ ์ธํ ๋ชจ๋ ๊ฒ์ ์ ๊ฑฐํ์ญ์์ค. ๊นจ๋ํ ์ฌ๋ ์ดํธ๋ก ์์ํ ๋ค์ ํ๋์ฉ ๋ค์ ์ถ๊ฐํ์ญ์์ค.