事件和 ref
# 事件和 ref
事件可以直接写到 DOM 节点,然后通过 ref 来获取 DOM 节点
import React from "react";
import ReactDOM from "react-dom";
class Component1 extends React.Component {
focusHandler() {
this.refs.name.focus();
}
render() {
return (
<div>
<input type="text" name="name" placeholder="" ref="name" />
<input
type="button"
name=""
value="focus"
onClick={this.focusHandler}
/>
</div>
);
}
}
ReactDOM.render(<Component1 />, document.getElementById("div1"));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 事件对象 —— event
React 在事件方法调用上默认会传一个形参events
,该对象是一个合成事件,所以不需要担心浏览器兼容的问题。
import React from "react";
import ReactDOM from "react-dom";
class Component1 extends React.Component {
submit(e) {
e.target.style.color = "red";
}
render() {
return <input type="button" value="submit" onClick={this.submit} />;
}
}
ReactDOM.render(<Component1 />, document.getElementById("app"));
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 事件 —— this 指针
在所有的事件当中,首先都要弄明白 this
指向哪里。而 React 事件中(如上面的案例)默认的 this
都是 undefined
,为了 this 指针能正确指回组件对象本身,通常可以用下面几种方法。
# 事件定义使用箭头函数
class Component1 extends React.Component {
submit = (e) => {
console.log(this);
e.target.style.color = "red";
};
render() {
return <input type="button" value="submit" onClick={this.submit} />;
}
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 事件调用时使用用箭头函数
class Component1 extends React.Component {
submit(e) {
console.log(this);
e.target.style.color = "red";
}
render() {
return (
<input type="button" value="submit" onClick={(e) => this.submit(e)} />
);
}
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 构造函数中使用 bind
class Component1 extends React.Component {
constructor(props) {
super(props);
this.submit = this.submit.bind(this);
}
submit(e) {
console.log(this);
e.target.style.color = "red";
}
render() {
return <input type="button" value="submit" onClick={this.submit} />;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 事件调用时用 bind
class Component1 extends React.Component {
submit(e) {
console.log(this);
e.target.style.color = "red";
}
render() {
return (
<input type="button" value="submit" onClick={this.submit.bind(this)} />
);
}
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 事件传参数
# 事件调用时使用用箭头函数
class Component1 extends React.Component {
submit(e, n) {
console.log(this, n);
e.target.style.color = "red";
}
render() {
return (
<input
type="button"
value="submit"
onClick={(e) => this.submit(e, 100)}
/>
);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 事件调用时用 bind
submit(n, e){
console.log(n)
e.target.style.color = 'red'
}
render(){
return <input type="button" value="submit" onClick={this.submit.bind(this, 20)}/>
}
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
编辑 (opens new window)
上次更新: 2023/09/07, 15:09:00