Skip to content

Commit 929c449

Browse files
committed
feat[ptr]: React 自定义组件想要触发DOM事件,得传递到能响应的元素上
同时注意如果没有特殊处理,在事件处理函数中,this指向undefined 1. bind 2. () =>
1 parent 84f3325 commit 929c449

1 file changed

Lines changed: 27 additions & 2 deletions

File tree

React/sandboxs/src/test/Event.js

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,36 @@ export function Btn() {
99
}
1010

1111
export class MyBtn extends React.Component {
12+
// 1.1
13+
// constructor(props) {
14+
// super(props)
15+
// this.handleClick = this.handleClick.bind(this)
16+
// }
17+
18+
handleClick() {
19+
// console.log(this) // undefined
20+
this.props.callback()
21+
this.props.onClick()
22+
}
23+
24+
// 2.1 用箭头函数那么事件处理函数不在原型上,而是在对象上
25+
handleClick2 = () => {
26+
this.props.callback()
27+
this.props.onClick()
28+
}
29+
1230
render() {
1331
return (
14-
<button onClick={this.props.callback}>
32+
// 1.2
33+
// <button onClick={this.handleClick.bind(this)}>
34+
35+
// <button onClick={this.handleClick2}>
36+
37+
// 2.2
38+
<button onClick={() => this.handleClick()}>
1539
点我
16-
</button>
40+
{/* <h1 onClick={this.props.onClick}>点我</h1> */}
41+
</button >
1742
)
1843
}
1944
}

0 commit comments

Comments
 (0)