learning/5.event/index.js

57 lines
1.3 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 在React与HTML不一样的地方是事件遵循驼峰命名规则
// function btnClick() {
// console.log("btn click...");
// }
// const e = <button onClick={btnClick}> test </button>
//
// ReactDOM.render(
// e,
// document.getElementById('root')
// );
// 与HTML不一样的地方html中 return false阻止默认行为 在React中必须调用 .preventDefault()方法
// function btnClick(e) {
// e.preventDefault();
// console.log("btn click...");
// }
// const e = <a href="#" onClick={btnClick}> test </a>
//
// ReactDOM.render(
// e,
// document.getElementById('root')
// );
// 显示绑定和隐式绑定
class TestTigger extends React.Component {
constructor() {
super();
this.state = {name: 'hello world'};
// 隐式绑定
this.btnClick = this.btnClick.bind(this);
}
btnClick() {
console.log("隐式绑定");
this.setState({name: '111'});
}
frontClick() {
console.log("显式绑定", this.state.name);
}
render() {
return (
<div>
<button onClick={this.btnClick}>隐式绑定</button>
<br/>
<button onClick={(e) => this.frontClick(e)}>显式绑定</button>
</div>
);
}
}
ReactDOM.render(
<TestTigger />,
document.getElementById('root')
);