📅  最后修改于: 2020-12-19 03:54:32             🧑  作者: Mango
状态是一种可更新的结构,用于包含有关组件的数据或信息,并且可以随时间变化。状态更改可以作为对用户操作或系统事件的响应而发生。这是React组件的核心,它决定了该组件的行为及其呈现方式。状态必须保持尽可能简单。它代表组件的本地状态或信息。它只能在组件内部或由组件直接访问或修改。
道具是只读组件。它是一个存储标记属性值的对象,其工作方式类似于HTML属性。它允许将数据从一个组件传递到其他组件。它类似于函数的参数,可以传递到组件的方式在函数中传递的参数相同。道具是不可变的,因此我们无法从组件内部修改道具。
SN | Props | State |
---|---|---|
1. | Props are read-only. | State changes can be asynchronous. |
2. | Props are immutable. | State is mutable. |
3. | Props allow you to pass data from one component to other components as an argument. | State holds information about the components. |
4. | Props can be accessed by the child component. | State cannot be accessed by child components. |
5. | Props are used to communicate between components. | States can be used for rendering dynamic changes with the component. |
6. | Stateless component can have Props. | Stateless components cannot have State. |
7. | Props make components reusable. | State cannot make components reusable. |
8. | Props are external and controlled by whatever renders the component. | The State is internal and controlled by the React Component itself. |
下表将指导您更改道具和状态。
SN | Condition | Props | State |
---|---|---|---|
1. | Can get initial value from parent Component? | Yes | Yes |
2. | Can be changed by parent Component? | Yes | No |
3. | Can set default values inside Component? | Yes | Yes |
4. | Can change inside Component? | No | Yes |
5. | Can set initial value for child Components? | Yes | Yes |
6. | Can change in child Components? | Yes | No |
注意:“状态”和“道具”组件具有一些共同的相似之处。下表中给出了它们。
SN | State and Props |
---|---|
1. | Both are plain JS object. |
2. | Both can contain default values. |
3. | Both are read-only when they are using by this. |