【问题标题】:How to use switch case in React?如何在 React 中使用 switch case?
【发布时间】:2023-02-25 00:49:02
【问题描述】:

常量计算器页面 = () => {

function calculate() {
    const firstNum = Number(document.getElementById('firstNum').value)
    const secondNum = Number(document.getElementById('secondNum').value)
    const symbol = document.getElementById('symbol').value
    const result = document.getElementById('result')
    console.log("im in");
    let res
    switch (symbol) {
        case "+": res = secondNumber + firstNumber
            
            break;
    
        default:
            break;
    }
   
    result.value = res

}

return (
    <div>
        <input id="firstNum" type="number" />
        <input id="symbol" placeholder="+" type="symbol" />
        <input id="secondNum" type="number" />
        <input id="result" type="number" />
        <button type="submit" onClick={calculate}>Go</button>
    </div>
)

}

这就是我使用它的方式,但它说 case 是一个禁止的词? 如何使用 switch case 以及我应该使用的语法是什么,我不想使用 if else 构造函数?

【问题讨论】:

  • 您收到的确切错误消息是什么?
  • 无论如何,您尝试使用secondNumberfirstNumber,但您有const secondNum(没有“ber”)和const firstNum(没有“ber”)

标签: javascript reactjs frontend calculator


【解决方案1】:

请检查一下,您的代码是正确的,只需要清理一下:

const Calculate = () => {
  function calculate() {
    const firstNum = Number(document.getElementById("firstNum").value);
    const secondNum = Number(document.getElementById("secondNum").value);
    const symbol = document.getElementById("symbol").value;
    const result = document.getElementById("result");
    console.log("im in");
    let res = 0;
    switch (symbol) {
      case "+":
        res = secondNum + firstNum;
        break;
      default:
        break;
    }
    result.value = res;
  }

  return (
    <div>
      <input id="firstNum" type="number" />
      <input id="symbol" placeholder="+" type="symbol" />
      <input id="secondNum" type="number" />
      <input id="result" type="number" />
      <button type="submit" onClick={calculate}>
        Go
      </button>
    </div>
  );
};

export default Calculate;

组件名称的第一个字母必须是大写字母

demo on codesandbox

【讨论】:

    【解决方案2】:

    你能尝试这个吗,我认为这也是一种更清洁的方法:在一个函数中将那个开关从渲染中取出,然后调用它传递你想要的参数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-22
      • 2010-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多