本文共 1543 字,大约阅读时间需要 5 分钟。
在 React 应用中,数据流是单向的,始终从父组件流向子组件。这种设计确保了数据的高效传播和管理。
state 是组件内部管理的数据,属于组件的私有属性。它可以包含多个键值对,动态地被修改,驱动 UI 的重新渲染。
在组件构造时,可以通过 this.state
初始化 state。例如:
class MyComponent extends React.Component { constructor() { super(); this.state = { text: '' }; }}
要更新 state,可以使用 this.setState()
方法。注意,setState
是一个异步函数,更新完成后会触发 render
方法,导致 UI 重新渲染。
在组件的 render
方法中,可以直接访问 this.state
来获取状态值,用于渲染 UI。
props 是组件接收的属性,通常由父组件传递给子组件。props 是单向的,从父到子传播,子组件无法改变父组件的 props。
子组件可以通过 props 接收父组件传递的数据。例如:
class ParentComponent extends React.Component { render() { return (); }}class ChildComponent extends React.Component { render() { return ( {this.props.prop1} - {this.props.prop2}); }}
props 是不可变的,父组件传递的值不会直接影响到子组件的 state。然而,子组件可以根据 props 的变化重新渲染。
在 React 组件开发中,constructor
和 super
的使用有特殊含义。
constructor
用于初始化组件的 state 和其他属性。在 ES6 中,组件的构造函数默认是 constructor
,如果不需要自定义构造逻辑,可以省略 constructor
。
super(props)
的作用是调用父组件的构造函数,确保 this.props
可以在子组件中访问。不要忘记在 constructor
中调用 super
。
class MyComponent extends React.Component { constructor() { super(); this.state = { count: 0 }; } // ...}
state 是组件内部管理的数据,属于组件的私有属性。它可以被多个子组件共享,通过 state 提升。
props 是组件接收的属性,通常由父组件传递给子组件。props 是单向的,从父到子传播,子组件无法改变父组件的 props。
转载地址:http://phqe.baihongyu.com/