我浏览了 react 的文档,关于受控和非受控组件。我创建了一个简单的用例,我想强制用户在输入字段中只输入大写值。
在第一种情况下,我使用 'ref' 和 'onChange' 来实现这一点,并使用全局对象的属性来捕获 dom 节点。这是它的代码 - https://jsfiddle.net/69z2wepo/78064/
class Nikhil extends React.Component {
constructor(props){
super(props);
this.field = {
input: ''
};
}
foo() {
this.y = this.field.input;
this.y.value = this.y.value.toUpperCase();
}
render() {
return (
<div>
<input ref={ node => this.field.input = node } onChange={ this.foo.bind(this) }/>
</div>
);
}
}
ReactDOM.render(<Nikhil/>,container);
Run Code Online (Sandbox Code Playgroud)
在第二种情况下,我使用了“value”属性和“onChange”状态。这是代码 - https://jsfiddle.net/69z2wepo/78066/
class Nikhil extends React.Component {
constructor(props){
super(props);
this.state = {
input: ''
};
}
foo(e) {
this.setState({ input: e.target.value.toUpperCase() });
} …Run Code Online (Sandbox Code Playgroud) reactjs ×1