我的 React 之旅:第 24 天
React 中的事件处理
**1. React 中的事件是什么?**
事件是用户或系统操作(例如,单击按钮、在字段中键入内容、将鼠标悬停在元素上等)。React 使用跨浏览器包装器来包装浏览器的原生事件,从而确保跨不同浏览器的一致性和兼容性。
**2. 我们如何在 React 中处理事件?**
React 中的事件处理涉及定义在事件发生时执行的“函数”(事件处理程序)”。
**示例语法:**
function handleEvent() { console.log('Event handled!'); } return ;
**3. 要记住的要点**
**4. React 中的常见事件**
**5. 多个事件的示例**
**学生.jsx:**
import PropTypes from 'prop-types'; export default function Student(props) { // Event Handlers function handleClick() { alert('Button clicked'); } function handleMouseEnter() { console.log('Mouse entered'); } function handleInputChange(event) { console.log('Input value:', event.target.value); } return (); } // PropTypes Student.propTypes = { name: PropTypes.string, age: PropTypes.number, isStudent: PropTypes.bool, }; // DefaultProps Student.defaultProps = { name: 'Guest', age: 0, isStudent: false, };Name: {props.name}
Age: {props.age}
Student: {props.isStudent ? 'Yes' : 'No'}
**6. 这里发生了什么?**
**7. 访问活动信息**
React 自动将事件对象传递给处理程序。
function handleClick(event) { console.log(event.target); // Logs the element that triggered the event } return ;
**8. 内联事件处理程序(可选)**
您可以直接在 JSX 中定义事件处理程序:
;
**为什么要避免使用内联函数?**
它们每次渲染组件时都会创建一个新的函数实例,这可能会影响性能。请谨慎使用它们。
**9. 在类组件中绑定 this**
在类组件中,绑定此以在事件处理程序中访问组件的上下文:
class App extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { console.log('Button clicked!'); } render() { return ; } }
**10.向事件处理程序传递参数**
要传递参数,请使用内联箭头函数:
function handleClick(name) { alert(`Hello, ${name}!`); } return ;