Props 是从父组件传入组件的输入(从子组件的角度来看是只读的)。State 是组件自己拥有和管理的内部数据(它可以改变它)。区别:props 来自外部,在组件内不会改变;state 是内部的且可变的。
Props — 传入,只读
jsx
() {
;
}
< name= />
Props 从父组件向下流向子组件。子组件读取它们,但不能改变它们——要改变 prop 的值,父组件必须传入一个新的。
function Counter() {
const [count, setCount] = useState(0); // `count` is this component's own state
return <button onClick={() => setCount(count + 1)}>{count}</button>;
// the component updates its OWN state via setCount
}
State 在组件内部创建并控制;组件改变它(通过 setCount/setState),改变它会触发重新渲染。
Props State
Source passed from parent created in the component
Mutable? read-only (in child) yes (via setter)
Who controls it the parent the component itself
Triggers render when the parent changes it when the component updates it
Purpose configure/pass data in track changing internal data
function Parent() {
const [user, setUser] = useState({ name: "Ann" }); // STATE in the parent
return <Child name={user.name} />; // passed DOWN as a PROP
}
一个组件的state 经常作为prop 传给子组件。状态提升和向下传递正是这种模式——父组件拥有 state,子组件以 prop 的形式接收它。
State 与 props 的区别是基于组件框架的基础。
它定义了数据所有权和流向:props 是外部的、只读的配置(数据向下);state 是组件管理的内部、可变数据。
混淆它们——修改 props,或将 props 复制到 state——会导致经典的 bug。
理解数据作为 props 向下流动,同时每个组件拥有自己的 state,这是 React/Vue/Angular 组件设计的基石。
一个包含详细解答的 IT 面试题库——从初级到高级。
捐赠