简体   繁体   English

如何在 onBlur 触发时向输入添加字符

[英]How to add characters to input when onBlur fires

I have an input field where I enter numbers我有一个输入字段,我可以在其中输入数字

When the onBlur fires, I need to add a % symbol to my numbers i have this function当 onBlur 触发时,我需要在我的数字中添加一个 % 符号我有这个功能

const onBlurValue = (day_index, value) => {
   const newBreakDownMonths = [...breakDownMonths];
   const day = newBreakDownMonths[nowMonth].break_down_days[day_index];
   if(value == "") {
      day.value = 0;
   } else {
      day.value = value;
   }
   setChangedDay(day);
}

I'll tell you briefly what it does.我将简要地告诉您它的作用。 When onBlur is triggered, if there is nothing in the input field, then there will be 0, if we enter numbers, it will save the numbers.当onBlur被触发时,如果输入框里什么都没有,那么就是0,如果我们输入数字,它会保存数字。

How to add % character to numbers when onBlur fires?如何在 onBlur 触发时向数字添加 % 字符? I have custom an input field that accepts events and a value -我自定义了一个接受事件和值的输入字段 -

<Input
  inputProps={{
    value: day.value,
    type: "number",
    step: "0.1",
    onKeyDown: (e) => detectKeyDown(e, day),
    onChange: (e) => onChangeValue(index, e.target.value),
    onFocus: (e) => onFocusValue(index, e.target.value),
    onBlur: (e) => onBlurValue(index, e.target.value),
    style: {
      marginTop: 0,
    },
  }}
/>;

Use a Hook to remember the value, and append % in the onBlur callback使用 Hook 记住值,并在onBlur回调中附加%

 const { useState } = React; const Example = () => { const [value, setValue] = useState(''); return ( <div> <h1>{'Example'}</h1> <input type='text' value={value} onChange={e => setValue(e.target.value)} onBlur={_ => setValue(value + ' %')} /> </div> ) } ReactDOM.render(<Example />, document.getElementById("react"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script> <div id="react"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM