代码之家  ›  专栏  ›  技术社区  ›  Ogglas

在没有警告的情况下清除html input type=“number”onFocus,或在没有值的情况下启动React TYPScript

  •  0
  • Ogglas  · 技术社区  · 7 年前

    我不想清除之前设置的html输入 onFocus 或者从一个空字段开始。

    salary: null 在构造函数中,页面加载时出现警告:

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

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

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

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

    我让它工作的唯一方法就是设置 salary: any 在里面 IState 然后设定 salary: '' 在构造函数中。我无法设定 salary: number | string 因为那样的话 Math.round 会给我一个打字错误。还有别的办法解决这个问题吗?

    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>
            );
        }
    }
    
    0 回复  |  直到 7 年前
        1
  •  0
  •   AL_1    5 年前

    你需要一个 Conditional (ternary) operator value={this.state.salary ? this.state.salary : "0"} 对于价值道具 FormControl 。这将删除输入为空的警告,您仍然可以在其他函数中使用它作为数字,如 Math.round()