高阶函数:
如果一个函数符合下面2个规范中的任何一个,那该函数就是高阶函数。
1.若A函数,接受的参数是一个函数,那么A就可以称之为高阶函数。
2.若A函数,调用的返回值依然是一个函数,那么A就可以称之为高阶函数
常见的高阶函数有:Promise、setTimeout、arr.map()等
案例(第2个规范)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>高阶函数</title>
</head>
<body>
<script src="../js/react.development.js"></script>
<script src="../js/react-dom.development.js"></script>
<script src="../js/babel.min.js"></script>
<div id="test"></div>
<script type="text/babel">
class Login extends React.Component{
state = {
username:'',
password:''
}
handelSubmit = (event)=>{
event.preventDefault();
const {username,password} = this.state;
alert(`用户名:${username},密码:${password}`)
}
formData = (dataType)=>{
return (event) => {
this.setState({[dataType]:event.target.value})
}
}
render(){
return(
<form onSubmit = {this.handelSubmit}>
用户名:<input onChange = {this.formData("username")} type="text"/><br/>
密码:<input onChange = {this.formData("password")} type="password"/><br/>
<button>登录</button>
</form>
)
}
}
ReactDOM.render(<Login/>,document.getElementById('test'))
</script>
</body>
</html>
上述案例不用高阶函数(函数柯里化)的写法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>不用函数柯里化</title>
</head>
<body>
<script src="../js/react.development.js"></script>
<script src="../js/react-dom.development.js"></script>
<script src="../js/babel.min.js"></script>
<div id="test"></div>
<script type="text/babel">
class Login extends React.Component{
state = {
username:'',
password:''
}
handelSubmit = (event)=>{
event.preventDefault();
const {username,password} = this.state;
alert(`用户名:${username},密码:${password}`)
}
formData = (dataType,event)=>{
// console.log(dataType,'dataType');
this.setState({[dataType]:event.target.value})
}
render(){
return(
<form onSubmit = {this.handelSubmit}>
用户名:<input onChange = {event => this.formData("username",event)} type="text"/><br/>
密码:<input onChange = {event => this.formData("password",event)} type="password"/><br/>
<button>登录</button>
</form>
)
}
}
ReactDOM.render(<Login/>,document.getElementById('test'))
</script>
</body>
</html>