如何在 React 15 中创建具有空默认值的受控输入 [英] How to create a controlled input with empty default in React 15
问题描述
我想要控制的文本输入有问题,但它需要支持空值.这是我的组件:
I'm having a problem with a text input that I want to be controlled, but it needs to support an empty value. Here is my component:
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.
When this is initially mounted, props.value is commonly (though not always) set to ''. This makes React 15 unhappy, as value='' makes the value get dropped, so React thinks it's an uncontrolled input, even though it has an onChange.
该组件可以工作,但我不喜欢在控制台中收到此警告:
The component works, but I don't like getting this warning in the console:
警告:FormControl 正在将文本类型的受控输入更改为不受控制.输入元素不应从受控切换到不受控制(反之亦然).决定使用受控或组件生命周期内不受控制的输入元素.更多的信息:http://facebook.github.io/react/docs/forms.html#control-组件
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 worked fine in 0.14.x without any warnings, but now 15 seems to not like it. How do I clean it up to keep the functionality but get rid of the warning?
推荐答案
确保 this.state.value
在挂载时不是未定义的.您可以通过设置 this.state = {value: props.value || 在构造函数中执行此操作''};
或通过使 props.value
成为必需属性.
ensure this.state.value
is not undefined on mount. You could do this in your constructor by setting this.state = {value: props.value || ''};
or by making props.value
a required property.
这篇关于如何在 React 15 中创建具有空默认值的受控输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!