如何在 React 15 中创建默认为空的受控输入

How to create a controlled input with empty default in React 15

我想要控制的文本输入有问题,但它需要支持空值。这是我的组件:

import React, { Component, PropTypes } from 'react';
import { ControlLabel, FormControl, FormGroup } from 'react-bootstrap';

const propTypes = {
  id: PropTypes.string.isRequired,
  label: PropTypes.string,
  onChange: PropTypes.func,
  upperCaseOnly: PropTypes.bool,
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};

export default class UppercaseTextField extends Component {
  constructor(props) {
    super();
    this.state = { value: props.value };
    this.onChange = () => this.onChange();
  }

  onChange(e) {
    let value = e.target.value;
    if (this.props.upperCaseOnly) {
      value = value.toUpperCase();
    }
    this.setState({ value });
    this.props.onChange(e);
  }

  render() {
    return (
      <FormGroup controlId={id}>
        <ControlLabel>{this.props.label}</ControlLabel>
        <FormControl
          type="text"
          onChange={this.onChange}
          defaultValue={this.props.value}
          value={this.state.value}
        />
      </FormGroup>
    );
  }
}

UppercaseTextField.propTypes = propTypes;

最初安装时,props.value 通常(但不总是)设置为 ''。这让 React 15 不高兴,因为 value='' 使值下降,所以 React 认为这是一个不受控制的输入,即使它有一个 onChange.

该组件有效,但我不喜欢在控制台中收到此警告:

Warning: FormControl is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: http://facebook.github.io/react/docs/forms.html#controlled-components

这在 0.14.x 中运行良好,没有任何警告,但现在 15 似乎不喜欢它。如何清理它以保留功能但消除警告?

确保 this.state.value 在装载时未定义。您可以通过设置 this.state = {value: props.value || ''}; 或使 props.value 成为必需的 属性.

在构造函数中执行此操作