React简单表单最佳实践
生活随笔
收集整理的这篇文章主要介绍了
React简单表单最佳实践
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
从一个简单表单谈起
假设我们要做一个表单,比如是这样,要怎么做?
你可能会这样写:firstName对应一个键盘记录,lastName对应一个键盘记录:
但这样写的话,复用性就会很差,如果我不是2个表格,而是20个表格呢?难道要绑定20个差异不大看起来十分类似的函数吗?
事实上,可以有更好的方案。正如之前看到的,事件对象的目标属性表示触发事件的输入框。因此,我们可以将输入框的名称和值作为变量。handleChange改造成如下形式:
handleChange({ target }) {this.setState({[target.name]: target.value,})}接着在渲染时为每个组件设置具体名称:
<input type="text" name="firstName" onChange={this.handleChange} /> <input type="text" name="lastName" onChange={this.handleChange} />完整代码如下:
import React from 'react'class Uncontrolled extends React.Component {constructor(props) {super(props)this.state = {firstName: '',lastName: '',}this.handleChange = this.handleChange.bind(this)this.handleSubmit = this.handleSubmit.bind(this)}handleChange({ target }) {this.setState({[target.name]: target.value,})}handleSubmit(e) {e.preventDefault()console.log(`${this.state.firstName} ${this.state.lastName}`)}render() {return (<form onSubmit={this.handleSubmit}><input type="text" name="firstName" onChange={this.handleChange} /><input type="text" name="lastName" onChange={this.handleChange} /><button>Submit</button></form>)}}export default Uncontrolled为表单设置默认值
但我们之前打开表单的时候,这个表单是没有默认值的。如果想要一打开的时候就添加默认值。一种思路是写成这样:
<input type="text" defaultValue="Hello React" />另外,我们还可以给state赋初值的方式来给默认值:
import React from 'react'class Controlled extends React.Component {constructor(props) {super(props)this.state = {firstName: 'Dan',lastName: 'Abramov',}this.handleChange = this.handleChange.bind(this)this.handleSubmit = this.handleSubmit.bind(this)}handleChange({ target }) {this.setState({[target.name]: target.value,})}handleSubmit(e) {e.preventDefault()console.log(`${this.state.firstName} ${this.state.lastName}`)}render() {return (<form onSubmit={this.handleSubmit}><inputtype="text"name="firstName"value={this.state.firstName}onChange={this.handleChange}/><inputtype="text"name="lastName"value={this.state.lastName}onChange={this.handleChange}/><button>Submit</button></form>)}}export default Controlled如果要多次点击
继续进一步探讨我们希望尽量减少写重复代码的思路。假如这个表单的Submit按钮点击一次和点击两次想要触发不同的效果呢?我们肯定不想去对每一种效果写一种handle函数,那有什么简单一点的方法吗?
handleEvent(event) {switch (event.type) {case 'click':console.log('clicked')breakcase 'dblclick':console.log('double clicked')breakdefault:console.log('unhandled', event.type)}} <button onClick={this.handleEvent} onDoubleClick={this.handleEvent}>Click me!</button>这样就可以实现我们的需求。
总结
以上是生活随笔为你收集整理的React简单表单最佳实践的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: React兄弟组件之间通信
- 下一篇: 性能优化:实现动画效果优先考虑css的t