React.js 中的非受控组件
在受控组件形式的数据中,数据由 React 组件处理,方法是对状态更新写入事件处理程序。但在非受控组件中,表单数据由 DOM 本身处理。
ref 用于从 DOM 中接收表单值。
示例
class UserNameForm extends React.Component {
constructor(props) {
super(props);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.inputUserName = React.createRef();
}
handleFormSubmit(event) {
console.log('username: ' + this.inputUserName.current.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleFormSubmit}>
<label>
Name:
<input type="text" ref={this.inputUserName} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}Reacts createRef 函数为表单字段创建一个引用,在表单提交时,我们可以通过 suing this.inputUserName.current .value 访问字段值。请注意在 ref 名称后使用current 。
它实际上是一个快速且有点糙的解决方案,代码较少,但控制较少。
使用非受控组件,React 提供了名为 defaultValue 的属性,以向表单字段提供初始值。
render() {
return (
<form onSubmit={this.handleFormSubmit}>
<label>
User Name:
<input
defaultValue="Steve"
type="text"
ref={this.inputUserName} />
</label>
<input type="submit" value="Submit" />
</form>
);
}文件输入类型始终是非受控组件,因为其值只能由用户设置,不能通过编程方式设置。
示例
文件输入的示例 −
class FileInputExample extends React.Component {
constructor(props) {
super(props);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.selectedFileInput = React.createRef();
}
handleFormSubmit(event) {
event.preventDefault();
console.log(
`Selected file - ${
this.selectedFileInput.current.files[0].name
}`
);
}
render() {
return (
<form onSubmit={this.handleFormSubmit}>
<label>
Upload file:
<input type="file" ref={this.selectedFileInput } />
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}
}
ReactDOM.render(
<FileInputExample />,
document.getElementById('root')
);
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP