event handling
-
Specify the event handler function through the onXxx attribute (note the case)
- React uses custom (synthetic) events instead of native DOM events - for better compatibility
- Events in React are handled through event delegation (delegating to the outermost element of the component - for more efficient
-
Get the DOM element object where the event occurred through event.target
Collect form data
- Uncontrolled components: Values cannot be controlled through code, only values can be manipulated through user behavior, and data can be processed through DOM nodes
- Controlled component: use React's state as the only source of data, and call the setState method to update the form input element of the data through the change function.
// 非受控组件
class Login extends React.Component{
showData = (event)=>{
event.preventDefault()//阻止表单提交
let {
username,password } = this
alert(`你的用户名是:${
username.value},你的密码是:${
password.value}`)
}
render(){
return (
<form action="http://www.baidu.com" onSubmit={
this.showData}>
<div>
<label>用户名:</label>
<input type="text" placeholder="请输入用户名" name="username" ref={
(c)=>{
this.username = c}}/>
</div>
<div>
<label>密码:</label>
<input type='password' placeholder="请输入密码" name="password" ref={
(c)=>{
this.password = c}}/>
</div>
<button>登录</button>
</form>
)
}
}
ReactDOM.render(<Login/>,document.getElementById("test"))
// 受控组件
class Login extends React.Component{
state = {
username:"",
password:""
}
showData = (event)=>{
event.preventDefault()//阻止表单提交
let {
username,password } = this.state
alert(`你的用户名是:${
username},你的密码是:${
password}`)
}
setUserName = (e)=>{
this.setState({
username:e.target.value
})
}
setPWD = (e)=>{
this.setState({
password:e.target.value
})
}
render(){
return (
<form action="http://www.baidu.com" onSubmit={
this.showData}>
<div>
<label>用户名:</label>
<input type="text" placeholder="请输入用户名" name="username" onChange={
this.setUserName}/>
</div>
<div>
<label>密码:</label>
<input type='password' placeholder="请输入密码" name="password" onChange={
this.setPWD}/>
</div>
<button>登录</button>
</form>
)
}
}
ReactDOM.render(<Login/>,document.getElementById("test"))
higher order functions
A function is a higher-order function if it meets either of the following two specifications:
- If the A function receives a parameter that is a function, then A is a higher-order function
- If the return value of function A is still a function, then A is a higher-order function
Common high-order functions are: Promise, setTimeout, arr.map(), etc.
currying of functions
By means of function calling and continuing to return functions, the function encoding form that receives parameters multiple times and finally processes them uniformly is realized