我需要使用函数将图像上传到我的useState,然后我想渲染此图像,问题是我不知道如何渲染返回的数组,这是代码 法典:
const [logoImg, logoUpdater] = useState();
const [title, updateTitle] = useState();
const [carouselImages, carouselImagesUpdater] = useState([]);
useEffect(
(e) => {
if (carouselImages.length > 0) {
}
},
[carouselImages]
);
const carouselUploader = (file) => {
var addedFile = file.target.files[0];
carouselImagesUpdater((carouselImages) => [...carouselImages, addedFile]);
};
const titleFunction = () => {
Preview(title);
};
return (
<div>
<div>
<p>Upload Carousel images</p>
<input
type="file"
accept="image/*"
multiple
onChange={(e) => carouselUploader(e)}
></input>
{carouselImages.map((img) => (
<img src={img} key="s"></img>
))}
多次重新渲染不会显示所选文件的损坏图像。下面是如何设置文件的示例:
const App = () => {
const [
carouselImages,
carouselImagesUpdater,
] = React.useState([]);
const carouselUploader = (e) => {
const reader = new FileReader();
reader.addEventListener('load', (event) => {
carouselImagesUpdater((carouselImages) => [
...carouselImages,
event.target.result,
]);
});
reader.readAsDataURL(e.target.files[0]);
};
return (
<div>
<p>Upload Carousel images</p>
<input
type="file"
accept="image/*"
multiple
onChange={(e) => carouselUploader(e)}
></input>
{carouselImages.map((img, index) => (
<img key={index} src={img}></img>
))}
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
以下是有关如何读取文件的一些文档。