【问题标题】:Random Number Generator in ReactReact 中的随机数生成器
【发布时间】:2021-11-17 06:44:50
【问题描述】:

我正在尝试使用具有最小和最大输入的 React(我是新手)做一个随机数生成器,但它不能很好地工作,它正在生成随机数但不在最大和最小之间

import React, { useState } from 'react';
import './style.css';

export default function PaginaInicial() {
  const [numeroAleatorio, setNumeroAleatorio] = useState(0);
  const [ValorMax, setValorMax] = useState(100);
  const [ValorMin, setValorMin] = useState(0);

  function BotaoMax() {
    var ValorMaximo = document.getElementById('max').value
    setValorMax(ValorMaximo);

  };
  function BotaoMin() {
    var ValorMinimo = document.getElementById('min').value
    setValorMin(ValorMinimo);
  };
  function gerarNumero() {
    const newNumber = parseInt(Math.random() * (ValorMax - ValorMin)) + ValorMin;
    setNumeroAleatorio(newNumber);
    if (ValorMax < ValorMin) {
      alert('Max value should be higher than Min value')
      setNumeroAleatorio('Error')
    };
  };

  return (
    <div className="conteudo-centralizado">
      <h3>Random Number:</h3>
      <div className="divNum">
      </div>

      <div>
        <input type="number" id='min' min='1' max='9999' placeholder="Número Mínimo" onChange={BotaoMin} />
        <input type="number" id='max' min='1' max='9999' placeholder="Número Máximo" onChange={BotaoMax} />
      </div>
      <h1>{numeroAleatorio}</h1>

      <div className='area-botao'>
        <label>
          Click on the following button to get a random number:
        </label>

        <button onClick={gerarNumero}>
          Generate Number
        </button>
      </div>
    </div>
  );
}

另外我来自巴西,所以有些词是葡萄牙语,对不起

【问题讨论】:

    标签: javascript html reactjs jsx


    【解决方案1】:

    CodeSandbox

    您需要将ValorMaximoValorMinimo 从字符串转换为数字。

    import React, { useState } from 'react';
    import './style.css';
    
    export default function PaginaInicial() {
      const [numeroAleatorio, setNumeroAleatorio] = useState(0);
      const [ValorMax, setValorMax] = useState(100);
      const [ValorMin, setValorMin] = useState(0);
    
      function BotaoMax() {
        var ValorMaximo = document.getElementById('max').value
        // Convert to number
        setValorMax(Number(ValorMaximo));
    
      };
      function BotaoMin() {
        var ValorMinimo = document.getElementById('min').value
        // Convert to number
        setValorMin(Number(ValorMinimo));
      };
      function gerarNumero() {
        const newNumber = parseInt(Math.random() * (ValorMax - ValorMin)) + ValorMin;
        setNumeroAleatorio(newNumber);
        if (ValorMax < ValorMin) {
          alert('Max value should be higher than Min value')
          setNumeroAleatorio('Error')
        };
      };
    
      return (
        <div className="conteudo-centralizado">
          <h3>Random Number:</h3>
          <div className="divNum">
          </div>
    
          <div>
            <input type="number" id='min' min='1' max='9999' placeholder="Número Mínimo" onChange={BotaoMin} />
            <input type="number" id='max' min='1' max='9999' placeholder="Número Máximo" onChange={BotaoMax} />
          </div>
          <h1>{numeroAleatorio}</h1>
    
          <div className='area-botao'>
            <label>
              Click on the following button to get a random number:
            </label>
    
            <button onClick={gerarNumero}>
              Generate Number
            </button>
          </div>
        </div>
      );
    }
    

    【讨论】:

    • 谢谢!不得不使用const newNumber = parseInt(Math.random() * (ValorMax - ValorMin)) + +ValorMin; 以及 Andriy 告诉
    • 没问题。而且您不需要在ValorMin 之前使用一元运算符+,因为ValorMin 已经是一个数字。请参阅答案中的 CodeSandbox。
    • 我更喜欢+,因为它更短,并且表现得几乎像Number()setValorMax(+document.getElementById('max').value)
    • 使用Number() 与一元+ 将字符串转换为数字与@ThiagoMM 面临的问题不同。
    【解决方案2】:

    您应该在 gerarNumero() 函数中添加 Math.floor() 函数。

    const newNumber = parseInt(Math.floor(Math.random() * (ValorMax - ValorMin) + ValorMin));

    请查看以下链接 https://futurestud.io/tutorials/generate-a-random-number-in-range-with-javascript-node-js

    【讨论】:

      【解决方案3】:

      您应该将ValorMin 转换为数字,因为 js 中的 1 + '1' = '11'。

      试试这个

      const newNumber = parseInt(Math.random() * (ValorMax - ValorMin)) + +ValorMin;
      

      【讨论】:

        【解决方案4】:

        react 中的命名函数不是响应式的,即它们被评估一次,如果该函数引用函数范围之外的值,它只会使用该变量的初始值,如果变量被更新,则函数不会被重新-初始化

        所以 genrarNmero 函数

        function gerarNumero() {
          const newNumber = parseInt(Math.random() * (ValorMax - ValorMin)) + ValorMin;
          setNumeroAleatorio(newNumber);
          if (ValorMax < ValorMin) {
            alert('Max value should be higher than Min value');
            setNumeroAleatorio('Error');
          }
        }
        

        ValorMaxValorMin 总是为 100 和 0

        您可以通过将 ValorMaxValorMin 作为参数传递给函数来解决此问题

        function gerarNumero(ValorMax, ValorMin) {
          const newNumber = parseInt(Math.random() * (ValorMax - ValorMin)) + ValorMin;
          setNumeroAleatorio(newNumber);
          if (ValorMax < ValorMin) {
            alert('Max value should be higher than Min value');
            setNumeroAleatorio('Error');
          }
        }
        

        或者您可以使用 useCallback 钩子进行反应,如果依赖关系发生变化,它将重新初始化函数

        const gerarNumero = useCallback(() => {
          const newNumber = parseInt(Math.random() * (ValorMax - ValorMin)) + ValorMin;
          setNumeroAleatorio(newNumber);
          if (ValorMax < ValorMin) {
            alert('Max value should be higher than Min value');
            setNumeroAleatorio('Error');
          }
        }, [ValorMax, ValorMin]);
        

        【讨论】:

        • 并且由于您使用 react 而不是使用查询选择器来更新 ValorMaxValorMin 的状态,因此您只需传入一个将事件传递给您的 onChange 属性的函数输入元素,例如&lt;input type="number" id='min' min='1' max='9999' placeholder="Número Mínimo" onChange={(e) =&gt; setValorMin(e.target.value)} /&gt;
        猜你喜欢
        • 1970-01-01
        • 2023-01-03
        • 1970-01-01
        • 2015-03-14
        • 1970-01-01
        • 2021-05-22
        • 2010-10-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多