html 输入框 "value" 属性 中的 If 语句

If statement inside "value" property of html input box

我下面有一个 <input> 方框,目前可以使用。我想知道我是否可以在 value 属性 中放置一个 if 语句。

             <input
                type="text"
                name="name"
                id="name"
                value={stockName.toUpperCase()}
                onChange={event => {
                  // Check that no numbers have been added 
                  const { value } = event.target;

                  if (/[^a-z]/gi.test(value)) { // Check that only letters are in the search
                    setError("Symbols should only contain letters!");
                  } else {
                    setError(null);
                    let uppercaseValue =  value.toUpperCase(); // Make sure its uppercase 
                    setStockName(uppercaseValue);
                  }
                }}/>

例如我想在 value 属性 中做这样的事情。

         value={event => {

              if (symbolSearchBool){ // If true 
                return symbolSearch // Set value to this, but still allow user to change it if needed
              }
              else { 
                return stockName.toUpperCase() // Set value to whatever user types in
              }
            }} 

有办法吗?

我正在为

使用 useState
      const [stockName, setStockName] = useState(); // Hold user input for stock Symbol 
      const [error, setError] = useState(null); // Hold error state based on poor user input

您的建议可以使用 ternary-operator

你的例子不起作用的原因是你声明了一个函数。通常,React 组件的 value 属性 不会尝试被调用(作为一个函数),而是应该是值本身。

这并不是说它不能。这只是违反惯例,您应该期望第三方组件 而不是 尝试调用您的 value 属性.


解决方案

 <input
   type="text"
   name="name"
   id="name"
   value={symbolSearchBool ? symbolSearch : stockName.toUpperCase()}
   onChange={event => { ... }}
/>

注意这里使用了三元运算符,语法为:
condition ? exprIfTrue : exprIfFalse

您可以这样阅读:

if (condition) {
  return exprIfTrue;
} else {
  return exprIfFalse;
}