直到现在我的代码是:
import React from 'react'
import {useEffect, useState} from 'react'
import {Container1, Container2, Font1, Font2, Font3, Button1, ImageCard, TextInput1} from '../styles/image_quiz_styles'
const Play = ({}) => {
const [reply, setReply] = useState('')
function renderImage(){
const myImages = [
{image:require('../img/apple.jpg')},
{image:require('../img/blackberry.jpg')},
{image:require('../img/cherry.jpg')},
]
const randomImage = [Math.floor(Math.random(myImages.length)*10)]
switch(randomImage){
case(0):
return {Image:require('../img/apple.jpg')}
break
case(1):
return {Image:require('../img/blackberry.jpg')}
break
case(2):
return {Image:require('../img/cherry.jpg')}
break
default:
}
}
return (
<Container1>
<Container2>
<Font2>Time:{time}</Font2>
</Container2>
<Font3>{reply}</Font3>
<ImageCard
source={require(renderImage)}
width='50'
height='50'
/>
</Container1>
)
}
export default Play
我想知道如何在我的代码中实现一种使用图像数组随机渲染三个图像的方法。我收到错误消息“ Invalid call require(renderImage)”。我想帮忙。
谢谢。
答案 0 :(得分:1)
基于注释中的Stuck想法,以下是您可以使用的代码示例:
import React, { Component, useState, useEffect } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import "./style.css";
const App = () => {
const [reply, setReply] = useState();
const [randomImage, setRandomImage] = useState('');
const renderImage = () => {
const myImages = [
{ image: 'https://picsum.photos/200/300' },
{ image: 'https://picsum.photos/200/300' },
{ image: 'https://picsum.photos/200/300' },
];
const randomImageIndex = Math.floor(Math.random() * Math.floor(3));
return myImages[randomImageIndex].image;
};
useEffect(() => {
setRandomImage(renderImage);
})
return (
<div>
<div>
</div>
<div>{reply}</div>
<img src={renderImage()} width="50" height="50" />
</div>
);
};
render(<App />, document.getElementById("root"));