简体   繁体   English

用空白值初始化 React 数字输入控件?

[英]Initializing React number input control with blank value?

I'd like my controlled input to initialize with no value in the box.我希望我的受控输入在框中没有任何值的情况下进行初始化。 The input is a number, so I don't pass in an empty '' .输入是一个数字,所以我不会传入一个空的'' Using defaultProps, I initialize the input with a null.使用 defaultProps,我用 null 初始化输入。

When typing into the input the console reports this message:在输入中输入时,控制台会报告此消息:

<MyInput> is changing an uncontrolled input of type number to be controlled. <MyInput>正在更改要控制的类型为 number 的不受控制的输入。 Input elements should not switch from uncontrolled to controlled (or vice versa).输入元素不应从不受控制切换到受控制(反之亦然)。

To prevent this normally I initialize with an empty string to prevent this "switching" from happening.为了防止这种情况,我通常用一个空字符串进行初始化,以防止这种“切换”发生。 But with a number (I don't want to show a 0, I want nothing to show) I am not sure how to do it.但是对于一个数字(我不想显示 0,我不想显示任何内容)我不知道该怎么做。

static defaultProps = {
    estimatedHours: null,
    estimatedMinutes: null,
  }

defalut values ^^默认值^^

<input
   type="number"
   onChange={(e) => this.handleChange('Hours', e.target.value)}
   onKeyDown={this.handleKeyDown}
   onPaste={this.handlePaste}
   value={estimatedHours}
   placeholder={hoursText}
   className="slds-input th-trailmix-textbox th-time-component__input"
/>

Simpler approach is to have a fallback value be an empty string.更简单的方法是将回退值设为空字符串。 Works for type=number as well.也适用于type=number

<input type="number" value={estimatedHours || ''} />

You can set value Undefined,您可以设置值未定义,

Also add a check for input type if required如果需要,还可以添加对输入类型的检查

class Input extends React.Component {

    constructor(props) {
        super(props);
        this.state = {value: undefined};

        this.handleChange = this.handleChange.bind(this);
    }

    handleChange = (event) => {
        const isnum = /^\d+$/.test(event.target.value);
        if (isnum) {
            return this.setState({
                value: Number(event.target.value),
            });
        }
    };

    render() {
        return (
            <input
                type="number"
                onChange={this.handleChange}
                value={String(this.state.value)}
                placeholder={"Please enter number"}
            />
        );
    }
}

and convert String to Number and vice versa并将字符串转换为数字,反之亦然

This won't throw you an error for uncontrolled input这不会因为不受控制的输入而引发错误

I'd like my controlled input to initialize with no value in the box.我希望我的受控输入在框中没有任何值的情况下进行初始化。

my problem is that I want a controlled number input with a null / undefined initial value.我的问题是我想要一个带有空/未定义初始值的受控数字输入。

I suggest defaulting the value props in the input element with an empty string like the following:我建议使用如下所示的空字符串默认输入元素中的 value props:

<input
   type="number"
   // ...
   value={estimatedHours === undefined ? '' : estimatedHours}
/>

This will make the input empty and prevent the warning from React.这将使输入为空并防止来自 React 的警告。 It'll also conveniently work well with the required prop too so the user must enter an input.它也可以方便地与required道具配合使用,因此用户必须输入输入。

In TypeScript 3.7+, it can be shorted to the following using the nullish coalescing operator :在 TypeScript 3.7+ 中,可以使用空合并运算符将其缩短为以下内容:

<input
   type="number"
   // ...
   value={estimatedHours ?? ''}
/>

Uncontrolled inputs are simply inputs where you aren't tying value to JavaScript.不受控制的输入只是您没有将value绑定到 JavaScript 的输入。 So if you are rendering:所以如果你正在渲染:

<input value={any} />

That is a controlled input.那是受控输入。

If you want to render an uncontrolled input with an empty value you could simply write如果你想用一个空值渲染一个不受控制的输入,你可以简单地写

<input type="number" /> or <input type="number" placeholder="" />
or <input type="number" placeholder="please enter a number..." />

Next, if you want to pull the value use a ref.接下来,如果您想拉取值,请使用 ref。

state = {
  query: ''
}

handleSubmit = (e) => {
  e.preventDefault()
  this.setState({ query: this.search.value })
}

render() {
  return (
    <form>
      <input 
        type="number" 
        ref={input => this.search = input} 
        placeholder="" 
      />
      <button type="submit" onClick={this.handleSubmit}>Submit</button>
    </form>
  )
}

Additionally, you can still perform logic on the return value if you need to.此外,如果需要,您仍然可以对返回值执行逻辑。 ie: IE:

handleSubmit = (e) => {
  e.preventDefault()
  this.setState({ query: this.search.value.toExponential(2) })
   // square whatever the user inputs and store in this.state.query
}

The easiest way to get the behaviour you are looking for is to define the prop type for this field to a string .获得您正在寻找的行为的最简单方法是将此字段的 prop 类型定义为string This will allow '' to be used as a default prop.这将允许''用作默认道具。 On form submission, you will need to make sure that the value of this field is parsed to a number.在提交表单时,您需要确保将此字段的值解析为数字。

type FormProps = {
  estimatedHours: string;
  estimatedMinutes: string;
}

FormProps.defaultProps = {
  estimatedHours: '',
  estimatedMinutes: '',
}

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

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