一,箭头函数的写法
- 行内写法
-
<button style={myStyle} onClick={()=>{alert(\'111\')}}>激活按钮0</button>
-
- 组件内写法
- 行内写法,需要写上this
-
export default class JumpEvent extends Component { activate3(para){ alert(para); }; render() { return ( <div> <button style={myStyle} onClick={()=>this.activate3(\'cc\')}>激活按钮3</button> </div> ) } }
- 页面内写法
- 不用写this,不能引用组件周期,this等方式
-
export default class JumpEvent extends Component { activate3(para){ alert(para); }; render() { return ( <div> <button style={myStyle} onClick={()=>activate1(\'cc\')}>激活按钮3</button> </div> ) } } function activate1(para){ alert(para); }
二,bind函数的写法
- 只能在组件内部方法绑定
-
<button style={myStyle} onClick={this.activate3.bind(this,\'ee\')}>激活按钮5</button>
三,阻止默认返回
- 使用preventDefalut
-
function ActionLink() { function handleClick(e) { e.preventDefault(); console.log(\'The link was clicked.\'); } return ( <a href=\"#\" onClick={handleClick}> Click me </a> ); }
四,箭头函数已经默认绑定
-
constructor(props) { super(props); this.state = {isToggleOn: true}; // 1,这边绑定是必要的,这样 `this` 才能在回调函数中使用 this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState(prevState => ({ isToggleOn: !prevState.isToggleOn })); } // 2,这个语法确保了 `this` 绑定在 handleClick 中 handleClick2 = (e) => { // 阻止默认的点击事件 e.preventDefault(); console.log(\'this is:\', this); }
版权声明
本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。


