在 HTML 中,表单的 element 像是 、 和 通常会维持它们自身的 state,并根据使用者的输入来更新 state。
因为 element 中有自己的 state,所以当要抓取 input text 里面的值,提交(给服务器,有後端程序跟资料库)储存时,方法有两种:
class NameForm extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {value: ''};
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
//直接绑定 value 资料,却绑 state 与 input 状态同步
render() {
return (
<form onSubmit={this.handleSubmit}>
<label> Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}}
注:setState 的非同步,可以看到 set 的 console.log 并不会即时显示 state 最新的值,反而是旧的,
所以可以用 componentDidUpdate 去看他已经更新 (如下图 DEMO,抓到的资讯可能是还没更新的)
class Clock extends React.Component {
constructor (props) {
super(props);
this.state = {
words: ''
}
this.handleUpdate = this.handleUpdate.bind(this);
this.input = React.createRef();
}
handleUpdate = () => {
this.setState({
words: this.input.current.value // 直接从 DOM 去抓取资料并存取
})
console.log('set:', this.state.words)
}
componentDidUpdate(prevProps) {
console.log('update:', this.state.words)
}
render() {
return (
<div>
<h1>Hello, Form!</h1>
<form>
<input type="text" onChange={this.handleUpdate} ref={this.input} placeholder="Insert some text" />
</form>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
参考资料:
https://zh-hant.reactjs.org/docs/forms.html
Controlled vs Uncontrolled Components in React
https://itnext.io/controlled-vs-uncontrolled-components-in-react-5cd13b2075f9
<<: [2021铁人赛 Day10] General Skills 07
>>: 【在厨房想30天的演算法】Day 10 资料结构:树 Tree
递回查询 Recursive Query 『递回查询』(Recursive Query)是指 当某个...
为什麽会接触到 OpenTelemetry,算是因为 Log 的追踪关系,在後台上有两三个 Spri...
forEach 来看看forEach在MDN的定义 Array.prototype.forEach(...
变数怎麽叫 今天起两天,会介绍一下在C++里面,每一个变数的叫法规则,他们在电脑里面是怎麽样储存的。...
「撰写完 dockerfile → 转成映像档 → 建立容器」的流程虽说不复杂,但随着要建立的容器一...