React-表单
在 HTML 中,表單元素(如<input>、 <textarea> 和 <select>)之類的表單元素通常自己維護 state,并根據用戶輸入進行更新。而在 React 中,可變狀態(mutable state)通常保存在組件的 state 屬性中,并且只能通過使用 setState()來更新。
我們可以把兩者結合起來,使 React 的 state 成為“唯一數據源”。渲染表單的 React 組件還控制著用戶輸入過程中表單發生的操作。被 React 以這種方式控制取值的表單輸入元素就叫做“受控組件”。<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>Learn React</title><script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script><script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script><!-- 生產環境中不建議使用 --><script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
</head><body><div id="root"></div><script type="text/babel">class FlavorForm extends React.Component {constructor(props) {super(props);this.state = {value: 'mango'};this.handleChange = this.handleChange.bind(this);this.handleSubmit = this.handleSubmit.bind(this);}handleChange(event) {this.setState({value: event.target.value});}handleSubmit(event) {alert('你喜歡的風味是: ' + this.state.value);event.preventDefault();}render() {return (<form onSubmit={this.handleSubmit}><label>選擇你喜歡的風味:<select value={this.state.value} onChange={this.handleChange}><option value="grapefruit">葡萄柚</option><option value="lime">酸橙</option><option value="coconut">椰子</option><option value="mango">芒果</option></select></label><input type="submit" value="提交" /></form>);}
}ReactDOM.render(<FlavorForm />, //JSX格式document.getElementById("root"));</script>
</body></html>
?
總結
- 上一篇: MongoDB中的读写锁
- 下一篇: React-状态提升