组件分类
-
!!!前端的组件化和模块化!!!
- 本质区别 组件化:侧重UI层面 模块化:侧重功能
-
在 React 中,组件分为 函数式组件(无状态组件) 和 class组件(有状态组件)
-
函数式组件(无状态组件)
- 使用 props 传值时,使用 props 属性名进行取用
-
class组件(有状态组件)
- 使用 class 定义,extends 继承 React Component,有state进行数据操作,也可以拥有 props,也有生命周期
- 必须使用 render 方法进行渲染html,因为是生命周期里面非常基础和底层的方法
- 通过 this.props 获取父组件给子组件的传值
- 使用 state 定义状态时,使用 this.state 属性名进行取用
-
一般情况,能使用无状态组件就使用无状态组件,否则用有状态组件;需要用到状态的就使用有状态组件
- 无状态组件会更少的消耗性能,因为没有状态,不走生命周期等;可以利用 hooks 实现状态的管理
- 如果有组件明确存储数据,并对数据进行修改,则更优先选择【有状态组件】
-
一般数据会通过父组件进行传递,这样就可以进行统一的数据管理,在父级尽心给一个集中的数据管理。以上是在没有使用 redux 的情况下,如果使用了 redux ,在 redux 中进行状态管理。
-
事件处理
-
setState 修改状态
- react 中没有实现类似于 Vue2中的Object.defineProperty或者Vue3中的proxy来监听数据的变化
- 所以需要通过 setState 通知 react改变状态
- setState 方法继承自 Component 中的Api,当我们调用 setState 时,会重新执行 render 方法
-
定义绑定事件
- 在 constructor 中修改 this
constructor() { super() this.changeAge.bind(this) }- 没有 constructor bind改变 this 指向
// 如果使用函数的形式直接定义,要在 constructor 中绑定 this 改变 this 的指向 <button onClick={ this.changeAge.bind(this) }>修改年龄</button>- 箭头函数改变 this 指向
// 方法二,用尖头函数改变 this指向 // 比较常用 changeMoney = () => { this.setState({ money: this.state.money + 1 }) } // 也可以直接绑定箭头函数 <button onClick={ () => this.changeMoney() }>修改money</button> -
修改组件状态
- 从父组件修改
// 子组件 function Login(props) { return <button>Login</button> } function Logout(props) { return <button>Logout</button> } state = { isLogin: false } render() { return <div> <h1>这是一个有状态组件</h1> { this.state.isLogin ? <Login /> : <Logout /> } <hr /> <button onClick={ this.updateState }>父组件改变组件</button> </div> }- 从子组件修改
// 子组件 function Login(props) { return <button onClick={ props.updated }>子组件改变状态Login</button> } function Logout(props) { return <button onClick={ props.updated }>子组件改变状态Logout</button> } state = { isLogin: false } updateState = () => { console.log('update') this.setState({ isLogin: !this.state.isLogin}) } render() { return <div> <h1>这是一个有状态组件</h1> { this.state.isLogin ? <Login updated={ this.updateState } /> : <Logout updated={ this.updateState } /> } <hr /> <button onClick={ this.updateState }>父组件改变组件</button> </div> }