我如何正确分配图像到状态和功能?

问题描述 投票:0回答:1

我是新手。我想创建一个使用随机数动态更改3张图像的函数。

示例:如果数字> 5 =图像1,如果数字> 10 =图像2,如果数字> 15 =图像3

我现在已经尝试了一些方法,但这就是我可以获得的最佳结果:enter image description here

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 + ")";
javascript reactjs state assign
1个回答
0
投票

这个想法是,您的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

© www.soinside.com 2019 - 2024. All rights reserved.