【问题标题】:Prevent Backspace to avoid erasing of initial value in text box in React防止退格以避免擦除 React 文本框中的初始值
【发布时间】:2019-02-15 07:54:36
【问题描述】:

我在我的项目中使用 antd。 代码是:

<FormItem  style={{'marginLeft':'-28px', 'marginTop':'10px'}}
>
 {getFieldDecorator('invoiceNumber', {
 initialValue: this.state.TxnNumber ? this.state.TxnNumber : "#",
  rules: [{                       
 required: false, message: 'Please Input Invoice!',
 }],
 })(
 <Input placeholder="S.O.NO#" style={{'width':'120px','height':'28px' }} onChange={(e)=>{e.preventDefault(); e.stopPropagation();                                   
 this.handleChange(0,e, 'invoiceNumber')}}  />
 )}                  
</FormItem>

handleChange = (index, e, field) => {
if(field == 'invoiceNumber')
    this.state.TxnNumber = e.target.value;
}

我希望符号“#”作为文本框中的初始值。还要防止退格删除“#”符号。 如何在 React 中做到这一点?

【问题讨论】:

    标签: reactjs textbox antd preventdefault


    【解决方案1】:

    只需使用受控输入,您就可以像这样在处理程序方法中控制输入的初始值:

    class App extends React.Component {
      constructor() {
        super();
        this.state = {
          value: '#'
        }
      }
    
      handleChange = ({ target: { value } }) => {
        this.setState({ value: value || '#'  })
      }
      
      render(){
        const { value } = this.state;
        
        return (
          <input
            value={value}
            onChange={this.handleChange}
          />
        )
      }
    }
    
    ReactDOM.render(<App />, document.getElementById('root'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="root"></div>

    【讨论】:

    • 这不适用于 antd。 handleChange 中显示“未定义值”错误
    • 这可能是状态初始化的问题。要么使用“传统”构造函数,要么(我认为更简单的方法)安装transform-class-properties babel 插件(并将其添加到.babelrc 的插件部分。)所以 state = { value: '#' } 部分将起作用。这只是constructor(){super(); this.state = {value: '#'} } 语法的分类。
    • @JaneFred,我用构造函数完成了我的回答。它现在对你有用吗?这种行为是否满足您的需求?谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多