当我删除setState
(在这种情况下为setImgDrag)时,状态不采用所选img的值,基本上我要做的是从边栏中获取img,而当onDragStart
时事件被触发后,我将img的scr并存储在一个名为imgDrag的var中,它可以完美工作,关键是当我尝试设置div中img的状态时,状态“ imgDrag”不会做好准备。如果您有更好的实现方式,我会接受的。
import Img from "./img-card"
const DropImg=()=>{
const [img,setImg]=useState([])
const[imgDrag,setImgDrag]=useState()
const[position,setPosition]=useState({x:0,y:0})
let imgSelected;
let getImg=(e)=>{
let img=e.target.files
for(let i=0;i<img.length;i++){
setImg((prevState)=>{return ( img? [...prevState,URL.createObjectURL(img[i])] : [...prevState]) })
}
}
let dragOver=(e)=>{
e.preventDefault()
let xPosition=e.clientX
let yPosition=e.clientY
setPosition(()=>{return {["x"]:xPosition,["y"]:yPosition}})
console.log(position)
}
let drop=(e)=>{
e.preventDefault();
setImgDrag(imgSelected)
console.log(imgDrag)
}
return (
<div className="flex bg-gray-400">
<div className=" bg-gray-800 w-1/4 rem-width-25 px-5 pt-6 h-screen">
<div className="block">
<div className="relative bg-teal-500 border rounded py-12 m-auto text-center w-11/12 text-white ">
<input type="file" id="img" className="absolute top-0 m-auto left-0 cursor-pointer bg-gray-200 border border-gray-300 mb-3 outline-none py-10 px-5 rounded shadow-sm opacity-0" multiple onChange={getImg} />
Click Here Or Drop An Image
</div>
</div>
<div className="grid w-full grid-cols-3 gap-2 mt-10">
{(img? img.map((src,index)=>{return <Img key={index} id={index} draggable="true" onDragStart={e=>{ imgSelected= e.target.src}} src={src}/>}):null)}
</div>
</div>
<div onDrop={drop} onDragOver={dragOver} className="w-9/12 h-screen">
{imgDrag? <Img src={imgDrag} style={{width:400}}/>: null}
{img? null:<p id="drop-here" className="text-center">Drop Image Here!</p>}
</div>
</div>)
}
export default DropImg
答案 0 :(得分:1)
使用变量imgSelected
似乎有问题,因此请尝试同时使用useState
。
// let imgSelected;
const [imgSelected, setImgSelected] = useState();
...
<div className="grid w-full grid-cols-3 gap-2 mt-10">
{(img? img.map((src,index)=>{
return <Img key={index}
id={index}
draggable="true"
// onDragStart={e=>{ imgSelected= e.target.src}}
onDragStart={e => setImgSelected(e.target.src) }
src={src}/>
}):null)
}
</div>