react非控制元件(Uncontrolled Component),基本上就跟一般的Html form很像,值不受state初使也沒有change callback管控。透過ref可以直接從DOM form取值,但無法像控制元件的同步效果,輸入透過callback setState再重新描繪UI,一切回歸傳統form操作。
src/FormRef.js
import React, { Component } from 'react';
class FormRef extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
console.log(this._name.value);
//console.log(this.refs.name.value);
e.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit} >
<p>
<label>
name:
<input type="text" ref={input => this._name = input} />
{/*
<input type="text" ref="name" />
*/}
</label>
</p>
<input type="submit" value="submit" />
</form>
);
}
}
export default FormRef;
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import FormRef from './FormRef';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<FormRef />, document.getElementById('root'));
registerServiceWorker();
參考資料:
Controlled and uncontrolled form inputs in React don't have to be complicated
https://goshakkk.name/controlled-vs-uncontrolled-inputs-react/