# 组件 & Props

* 组件允许你将 UI 拆分为独立可复用的代码片段，并对每个片段进行独立构思
* 组件，从概念上类似于 JavaScript 函数，它接受任意的入参 Props，并返回用于描述页面展示内容的 React 元素

## 函数组件与class组件

* 定义组件最简单的方式就是编写 JavaScript 函数
* 也可以使用 ES6 的 class 来定义组件

  \`\`\`jsx harmony

function Welcome(props) { return Hello, {props.name} }

class Welcome extends React.Component { render() { return Hello, {this.props.name} } }

````
## 渲染组件

* 组件名称必须以大写字母开头
* 当 React 元素为用户自定义的组件时，它会将 JSX 所接收的属性 attributes 以及子组件 children 转换为单个对象传递给组件，这个对象被称为 props
```jsx harmony

function Welcome(props) {
    return <h1>Hello, {props.name}</h1>
}

const element = <Welcome name="Sara" />
ReactDOM.render(
    element,
    document.getElementById('root')

)
````

* 在上面这个例子中发生了什么？
  1. 调用 ReactDOM.render() 函数，并传入  作为参数
  2. React 调用 Welcome 组件，并将 {name: 'Sara'} 作为 props 传入
  3. Welcome 组件将 Hello, Sara 元素作为返回值
  4. React DOM 将 DOM 高效地更新为 Hello, Sara

## 组件组合

* 组件可以在其输出中引用其他组件
* 通常来说，每个新的 React 应用程序的顶层组件都是 APP 组件

## 提取组件

* 将组件拆分为更小的组件
* 建议从组件自身的角度命名 props，而不是依赖调用组件的上下文命名

## Props 的只读性

* 组件无论是使用函数声明还是通过 class声明，都决不能修改自身的 props
* 所有 React 组件都必须像纯函数一样保护它们的 props 不被修改


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://zg-zhang.gitbook.io/note/react/offical-website/main-concepts/component-and-props.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
