React 组件学习笔记
在 React 中,组件是构建用户界面的基本单元。组件可以被视为 JavaScript 函数,它们接受输入并产生输出。一个简单的 React 组件可以如下定义:
jsxCopy Codefunction Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
在上面的代码中,我们定义了一个名为 Greeting
的组件,它接受一个名为 props
的参数,并返回一个包含欢迎消息的 h1
元素。我们可以使用该组件如下进行渲染:
jsxCopy Code<Greeting name="Alice" />
这将产生一个如下所示的输出:
Copy CodeHello, Alice!
类型定义和 Props
在 React 中,我们可以使用 TypeScript 或 Flow 等类型检查工具来增强代码健壮性。我们可以通过定义类型来明确组件所需的 props
的类型,例如:
tsxCopy Codetype GreetingProps = {
name: string;
};
function Greeting({ name }: GreetingProps) {
return <h1>Hello, {name}!</h1>;
}
在上面的代码中,我们定义了一个类型 GreetingProps
来表示 Greeting
组件所需的 props
,然后我们在组件中使用解构赋值来获得 name
属性,并将其显示在 h1
元素中。
状态和生命周期方法
除了 props
外,React 中的组件还可以使用状态来管理内部数据。我们可以使用 useState
Hook 来定义状态,例如:
jsxCopy Codefunction Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
}
在上面的代码中,我们定义了一个名为 Counter
的组件,它使用 useState
Hook 来定义一个名为 count
的状态和一个名为 setCount
的函数来更新该状态。我们也定义了一个名为 handleClick
的函数,它将 count
状态的值加 1,并用一个按钮来触发该函数。当渲染该组件时,我们会得到一个包含计数器和一个增加计数器的按钮的 UI。
React 组件的生命周期方法可以帮助我们在组件挂载、更新或卸载时执行特定的代码。例如,我们可以使用 useEffect
Hook 来执行副作用操作,例如向服务器发送请求或订阅外部事件:
jsxCopy Codefunction UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`/api/users/${userId}`)
.then(response => response.json())
.then(user => setUser(user))
.catch(error => console.error(error));
}, [userId]);
if (!user) {
return <p>Loading user...</p>;
}
return (
<div>
<p>Name: {user.name}</p>
<p>Email: {user.email}</p>
</div>
);
}
在上面的代码中,我们定义了一个名为 UserProfile
的组件,它接受一个名为 userId
的属性,并使用 useState
Hook 定义了一个名为 user
的状态。然后,我们使用 useEffect
Hook 发送请求并将结果存储在 user
状态中。在渲染时,如果 user
为空,则显示“加载用户”的消息,否则显示用户的名称和电子邮件。
实例
以下是一个使用 React 组件构建的简单应用程序,该应用程序显示若干个图像,并允许用户搜索图像。
jsxCopy Codeimport { useState, useEffect } from 'react';
function ImageGallery() {
const [images, setImages] = useState([]);
const [searchTerm, setSearchTerm] = useState('');
useEffect(() => {
fetch(`https://api.unsplash.com/search/photos?query=${searchTerm}&per_page=9`, {
headers: {
Authorization: 'Client-ID YOUR_ACCESS_KEY'
}
})
.then(response => response.json())
.then(data => setImages(data.results))
.catch(error => console.error(error));
}, [searchTerm]);
function handleSearch(event) {
event.preventDefault();
const searchTerm = event.target.elements.search.value;
setSearchTerm(searchTerm);
}
return (
<div>
<form onSubmit={handleSearch}>
<input type="text" name="search" placeholder="Search images" />
<button type="submit">Search</button>
</form>
<div>
{images.map((image, index) => (
<img key={index} src={image.urls.small} alt={image.alt_description} />
))}
</div>
</div>
);
}
在上面的代码中,我们使用 useState
Hook 定义了 images
和 searchTerm
状态。然后,我们使用 useEffect
Hook 发送请求以获取图像,并将结果存储在 images
状态中。我们还定义了一个名为 handleSearch
的函数,它在表单提交时触发,并使用输入字段的值来更新 searchTerm
状态。最后,我们在 UI 中显示一个搜索表单和一个图像列表。
这是一个简单的示例,它演示了如何使用 React 组件创建交互式应用程序。