为什么只返回最后一个点击的img文件


const [photo, setPhoto] = React.useState([]);
const addPhoto = async (e) => {
await setPhoto(e.target.files);
};
const returnPhoto = () => {
if (photo.length > 0) {
for (let i = 0; i < photo.length; i++)  {
return(
<div style={{background: '#303030', display: 'inline-flex'}}>
<img alt='pic' style={{maxHeight: '10em', maxWidth: '10em'}} src={URL.createObjectURL(photo[i])}/>
</div>
)}}}

有人看到我做错了什么吗?我正在尝试返回useState的当前选定文件。。。我想我应该更改addPhoto((函数,但到目前为止我还不知道如何更改。

您的主要问题是将return放入常规for循环中会在第一次迭代时退出循环。您可能希望使用类似map()的东西来返回一个JSX元素数组。

因为files属性是FileList,所以不能直接使用map(),但可以将其转换为数组。

您也可以通过备忘录化创建的URL 来优化这一点

const [ photos, setPhotos ] = useState([]); // really think this should be plural
const addPhoto = (e) => { // no need for async
setPhotos(e.target.files);
};
// photos is a FileList so convert to an array
const photoUrls = useMemo(() =>
Array.from(photos, URL.createObjectURL), [ photos ]);
useEffect(() => () => {
// cleanup
photoUrls.forEach(URL.revokeObjectURL);
}, [ photoUrls ]);
const returnPhoto = () => photoUrls.map(url => (
<div style={{background: "#303030", display: "inline-flex"}}>
<img
src={url}
alt="pic"
style={{maxHeight: "10em", maxWidth: "10em"}}
/>
</div>
));

最新更新