我是新手。我想创建一个使用随机数动态更改3张图像的函数。
示例:如果数字> 5 =图像1,如果数字> 10 =图像2,如果数字> 15 =图像3
random(min,max,x) {
min = Math.ceil(5);
max = Math.floor(20);
return x = Math.floor(Math.random() * (max - min)) + min;
}
colormachine = () => {
if(this.random(this.props.x > 8))
{
this.setState(state => ({color: green}));
};
}
render() {
console.log(this.random());
// console.log(this.colormachine());
({ color: green })
是一个
const green = { backgroundImage: "url(" + tirelogogreen + ")";
这个想法是,您的state
应该只包含非常简单的数据,而与样式无关。例如,我在这里存储一个数字。
const [myNum, setMyNum] = useState(0);
然后我有一个更新状态的按钮:
<button onClick={() => setMyNum(Math.floor(Math.random() * 20))}>
然后,您的组件将根据数字决定如何处理。
function Box(props) {
// here i am getting different style based on what's being passed in
const getStyle = myNum => {
if (myNum > 4 && myNum < 10) return { backgroundColor: "green" };
if (myNum > 10 && myNum < 15) return { backgroundColor: "blue" };
if (myNum > 14) return { backgroundColor: "red" };
return null;
};
return (
<div className={"square"} style={getStyle(props.colorNum)}>
<div className={"content"}>I'm a square.</div>
</div>
);
}
有关工作示例,请单击此处:https://codesandbox.io/s/react-boilerplate-h2dbd