【问题标题】:Clear html input type="number" onFocus without warning or start without a value React TypeScript清除 html 输入 type="number" onFocus 没有警告或开始没有值 React TypeScript
【发布时间】:2018-10-29 22:03:24
【问题描述】:

我既不想清除以前设置的数字onFocus 的 html 输入,也不想从空字段开始。

salary: null 在页面加载时的构造函数警告:

警告:input 上的 value 属性不应为空。考虑使用 空字符串清除组件或undefined 不受控制 组件。

salary: undefined 在构造函数中,然后开始在输入字段中输入:

警告:组件正在更改类型为 number 的不受控制的输入 被控制。输入元素不应从不受控制的状态切换 控制(反之亦然)。决定使用受控或 在组件的生命周期内不受控制的输入元素。更多的 信息:https://reactjs.org/docs/forms.html#controlled-components

salary: 0 在构造函数中,onFocus={() => this.setState({salary: null})} 在输入字段中,当我单击该字段时,我得到上面的两个错误,0 仍然存在于输入字段中。

我让它工作的唯一方法是在IState 中设置salary: any,然后在构造函数中设置salary: ''。我无法设置salary: number | string,因为像Math.round 这样的函数会给我一个TypeScript 错误。有没有其他方法可以解决这个问题?

import * as React from "react";
import { FormControl } from "react-bootstrap"

interface IProps {    
}

interface IState {
    salary: number
}

export class Taxes extends React.Component<IProps, IState> {
    constructor(props: IProps) {
        super(props);
        this.state = {
            salary: 0,
        }
    }

    handleChange = (event: any) => {
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;

        this.setState({
            [name]: value
        });
    }

    render() {
         return (
            <div>
                <FormControl
                    name="salary"
                    type="number"
                    value={this.state.salary}
                    onChange={this.handleChange}
                    //onFocus={() => this.setState({salary: 0})}
                />
            </div>
        );
    }
}

【问题讨论】:

  • Math.round(parseInt(salary))这样的事情怎么样?
  • @bennygenel 我需要在任何我使用salary 的地方做parseInt。在这种情况下,我选择了any

标签: javascript html reactjs typescript


【解决方案1】:

您可以使用 Conditional (ternary) operator value={this.state.salary ? this.state.salary : "0"} 作为 FormControl 的 value 属性。这将消除输入为 null 的警告,您仍然可以将其用作其他函数中的数字,例如 Math.round()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多