【问题标题】:How can I pick a random border color in react?如何在反应中选择随机边框颜色?
【发布时间】:2020-06-15 03:41:26
【问题描述】:

我很想为这个问题提供一些帮助。我正在尝试尝试为我打印的每个字符选择随机 border-color

这是代码:

const style = {
    padding: '16px',
    margin: '12px',
    border: '*** I want to insert a random color in here***'
    textAlign: 'center',
    display: 'inline-block',
    transition: '0.2s ease-in',
}

关于什么是最好的清洁方法有什么建议吗?

【问题讨论】:

标签: javascript css reactjs random


【解决方案1】:

只需使用Math.random 选择三个数字(然后可能会想要向下取整)。我觉得生成 255 以下的三个数字比生成一个十六进制字符串更容易,因为使用数字生成器生成的数字非常大。不过,这只是我的直觉,不知道它是否会对性能产生影响。

// just for brevity, I would do this inline in practice.
const random = () => Math.floor(Math.random() * 255));

const style = {
    padding: '16px',
    margin: '12px',
    border: `rgb(${random()}, ${random()}, ${random()})`, // <--
    textAlign: 'center',
    display: 'inline-block',
    transition: '0.2s ease-in',
}

【讨论】:

    【解决方案2】:

    MDN你可以得到边框样式

    然后创建一个函数,获取介于 0 和数组中边框样式数之间的随机数,该数将是您使用 style 对象中的字符串模板传递给边框类型数组的索引

    const borderStyles = ["none", "dotted", "dashed", "solid", "double", "groove"];
    
    function getIndex() {
      return Math.floor(Math.random() * borderStyles.length);
    }
    
    const style = {
      padding: "16px",
      margin: "12px",
      border: `${borderStyles[getIndex()]}`,
      textAlign: "center",
      display: "inline-block",
      transition: "0.2s ease-in",
    };
    
    console.log(style.border);

    【讨论】:

      【解决方案3】:

      如果您只想更改颜色,请按照此操作。我保持边框宽度为 1px 且实心。

      var randomColor = '#' + Math.floor(Math.random()*16777215).toString(16);
      
      const style = {
        padding: '16px',
        margin: '12px',
        border: `1px solid ${randomColor}`,
        textAlign: 'center',
        display: 'inline-block',
        transition: '0.2s ease-in',
      }
      

      【讨论】:

        【解决方案4】:

        那里!好吧,我认为您可以做到的一种方法是首先创建三个随机数介于 0 和 255 之间的变量,然后将每个值分配给您的样式变量。使用插值将变量与字符串结合起来:

        let r = Math.floor(Math.random() * 256);
        let g = Math.floor(Math.random() * 256);
        let b = Math.floor(Math.random() * 256);
        
        const style = {
        //your code
        border: `rgb(${r}, ${g}, ${b})`,
        //more code
        }
        

        我真的希望这有效!

        【讨论】:

          【解决方案5】:

          尝试以下方法:-

          const style = {
              padding: '16px',
              margin: '12px',
              border: '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16),
              textAlign: 'center',
              display: 'inline-block',
              transition: '0.2s ease-in',
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2019-03-29
            • 2020-07-16
            • 2012-08-24
            • 2019-09-06
            • 2019-10-29
            • 1970-01-01
            • 2021-09-29
            • 1970-01-01
            相关资源
            最近更新 更多