saveFormData = (key) => {
console.log(key)
}
{/* 把saveFormDate作为回调函数给onChange调用 */}
<input type="text" placeholder='请输入姓名' onChange={this.saveFormData}/>
{/* 把saveFormDate的返回值作为onChange回调,因为没有返回值, 所以相当于把undefined给onChange作为回调, 所以不生效 */}
<input type="text" placeholder='请输入姓名' onChange={this.saveFormData('userName')}/>
1. 举例
第一种方法:
import React from 'react'
class App extends React.Component {
//初始化状态
sate={
userName:'',
password:''
}
saveFormData = (event,key) => {
this.setState({
[key]:event.target.value
})
}
login = (event) => {
event.preventDefault() //阻止表单提交
const {userName, password} = this.state;
alert(`姓名:${userName},密码:${password}`)
}
render() {
return (
<form onSubmit={this.login}>
<input type="text" placeholder='请输入姓名' onChange={ e => {this.saveFormData(e,'userName')}}/>
<br />
<input type="password" placeholder='请输入密码' onChange={ e => {this.saveFormData(e,'password')}}/>
<br />
<button >登录</button>
</form>
);
}
}
export default App;
第二种写法:
import React from 'react'
class App extends React.Component {
//初始化状态
sate={
userName:'',
password:''
}
saveFormData = (event) => {
const key = event.target.name;
this.setState({
[key]:event.target.value
})
}
login = (event) => {
event.preventDefault() //阻止表单提交
const {userName, password} = this.state;
alert(`姓名:${userName},密码:${password}`)
}
render() {
return (
<form onSubmit={this.login}>
<input type="text" placeholder='请输入姓名' onChange={this.saveFormData} name='userName'/>
<br />
<input type="password" placeholder='请输入密码' onChange={this.saveFormData} name='password'/>
<br />
<button >登录</button>
</form>
);
}
}
export default App;
第三种:
import React from 'react'
class App extends React.Component {
//初始化状态
sate={
userName:'',
password:''
}
saveFormData = (key) => {
return (event) =>{
this.setState({
[key]:event.target.value
})
}
}
login = (event) => {
event.preventDefault() //阻止表单提交
const {userName, password} = this.state;
alert(`姓名:${userName},密码:${password}`)
}
render() {
return (
<form onSubmit={this.login}>
<input type="text" placeholder='请输入姓名' onChange={this.saveFormData('userName')}/>
<br />
<input type="password" placeholder='请输入密码' onChange={this.saveFormData('password')} />
<br />
<button >登录</button>
</form>
);
}
}
export default App;
2. 高阶函数的概念:
高阶函数:如果一个函数符合下面2个规范中的任何一个,那么该函数就是高阶函数
若函数A: 接收的参数是一个函数,那么函数A就可以称为高阶函数;
若函数A: 调用的返回值依然是一个函数, 那么函数A就可以称之为高阶函数;
saveFormData = (key) => {
return (event) =>{
this.setState({
[key]:event.target.value
})
}
}
常见的高阶函数: :::success
- Promise: new Promise((resave, reject) => {})
- setTimeout: setTimeout(() => {}, 100)
- 数组常用方法:map,find, filter…
:::
3. 函数柯里化:
函数柯里化: 通过函数调用继续返回函数的方法, 实现多次接收参数最后统一处理的函数编写形式。
比如一个add函数正常这样写:
函数柯里化这样写:function add(a,b,c){
return a + b + c;
}
console.log(add(1,2,3))
```javascript saveFormData = (key) => { return (event) =>{function add(a){
return (b) => {
return (c) => {
return a+b+c
}
}
}
console.log(add(1)(2)(3))
this.setState({
[key]:event.target.value
})
}
} ```