React函数组件与状态管理详解
1. 函数组件入门
1.1 “Hello World”示例与 children
属性
在使用代码时,你可能会好奇“Hello World”字符串是如何被放置在 Title
组件下的。实际上,这个字符串是通过 children
属性与组件连接的。以下是 Title
组件的定义:
const Title = ({ children }) => {
return <h1>{children}</h1>
}
本质上, App
组件会将“Hello World”赋值给 children
属性,然后调用 Title
组件实例。如果在定义 Title
组件时忘记包含 children
属性,“Hello World”将被忽略, App
组件会简化为:
const Title = () => {
return <h1>Haha, you got me</h1>
}
const App = () => {
return <Title />
}
显