Skip to content

ReactJS - 事件

本章我们将探讨如何在 React 中处理事件。React 事件使用 camelCase(驼峰命名法)命名,而不是小写字母(例如 onClick 而不是 onclick)。在 JSX 中,你将一个函数作为事件处理器传递,而不是一个字符串。

此示例演示了函数式组件中的一个简单事件处理器。我们使用 useState Hook 来管理一部分数据。按钮上的 onClick 事件触发 updateData 函数,该函数随后更新组件的状态。

import React, { useState } from 'react';
function App() {
const [data, setData] = useState('Initial data...');
const handleUpdateData = () => {
setData('Data updated!');
};
return (
<div>
<button onClick={handleUpdateData}>CLICK ME</button>
<h4>{data}</h4>
</div>
);
}
export default App;
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';
const container = document.getElementById('app');
const root = createRoot(container);
root.render(<App />);

当你点击 ‘CLICK ME’ 按钮时,它下面的文本将从 ‘Initial data…’ 变为 ‘Data updated!’。

React 中一个常见的模式是父组件管理状态,并将函数传递给子组件,子组件可以触发父组件的状态更新。子组件通过 props 接收此函数,并在特定事件发生时调用它。

import React, { useState } from 'react';
// 子组件
const Content = (props) => {
return (
<div>
<button onClick={props.onUpdateData}>CLICK IN CHILD</button>
<h3>{props.currentData}</h3>
</div>
);
}
// 父组件
function App() {
const [data, setData] = useState('Initial data from parent...');
const handleUpdateDataFromChild = () => {
setData('Data updated from the child component!');
};
return (
<div>
<Content
currentData={data}
onUpdateData={handleUpdateDataFromChild}
/>
</div>
);
}
export default App;
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';
const container = document.getElementById('app');
const root = createRoot(container);
root.render(<App />);

在这种设置中,点击 ‘CLICK IN CHILD’ 按钮(由 Content 组件渲染)将调用 App 组件中的 handleUpdateDataFromChild 函数。这会更新 App 中的 data 状态,新的数据(‘Data updated from the child component!’)将显示在 Content 组件中。这演示了父子组件之间的单向数据流和事件处理。