Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of React event handling

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

小编给大家分享一下React事件处理的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

React的事件处理和DOM的事件处理是很相似的,只是有一些语法上的区别:

React的事件名是驼峰的,不是小写的

在JSX语法中,你传递一个fucntion作为时间处理器,而不是一个string

举个例子:

Activate Lasers

而且如果你想拿到事件对象event,这个对象是React按照w3c标准完成的,所以不用担心浏览器的兼容性,可以像如下这样:

function ActionLink() { function handleClick(e) { e.preventDefault(); console.log('The link was clicked.'); } return ( Click me );}

如果用ES6的class写法可以像如下一样:

class Toggle extends React.Component { constructor(props) { super(props); this.state = {isToggleOn: true}; // 这个`this`绑定是有必要的,用来让this可以在回调中被正确指向React组件的实例对象 this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState(prevState => ({ isToggleOn: !prevState.isToggleOn })); } render() { return ( {this.state.isToggleOn ? 'ON' : 'OFF'} ); }}ReactDOM.render( , document.getElementById('root'));

还有两种方式可以避免写显式bind(this) ,但是都不推荐这么用啊~

以上是"React事件处理的示例分析"这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report