React---第二弹

第二弹

useState

使用范围: function 定义的组件中,

作用: 主要设置局部状态,

有两个返回值

  1. 局部状态名字
  2. 改变状态的方法
const { useState } = React;
function Counter() {
  const [count, setCount] = useState(0);

  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

ReactDOM.render(<Counter />, document.getElementById("app"));

父组件传子组件

核心: 父传子通过:属性传递
通过 props 属性把相应的数据和 function 传递给子组件,在子组件中可以直接访问 props 中的数据和调用 function 向父组件传参

  const element=<div>
      <h5>步长为:1</h5>
        <Counter step={1} p={{ color: "red", size: 30 }} {...people} />
  </div>

子组件传父组件

核心:子传父通过:方法调用

this.setState 改变state中的数据

this.setState 是异步触发的;
有两个参数;
第一个参数表示:数据值;
第二个参数表示:数据值改变后执行的回调函数。

this.setState({ count: this.state.count + this.props.step }, function() {
  if (changeParentData) {
    changeParentData(this.state.count);
  }
});

react 创建脚手架项目

方一:

npx create-react-app first-app # 创建一个react项目
npm start # 启动项目
# or
yarn start # 启动项目


# react创建的项目中集成了测试框架jest

# 单元测试: 就是我们把代码的功能做最小化的拆分,对每一个功能点写测试用例

方二:

  npm i create-react-app -g # 全局安装脚手架
  create-react-app first-app # 创建项目
  npm start # 启动项目
  # or
  yarn start # 启动项目

react 生命周期

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1JHDoZ1u-1578205130045)(https://s2.ax1x.com/2019/12/17/Qo8qfg.png)]

注意:
主要针对 shouldComponentUpdate 方法做组件性能优化。
true 会执行更新阶段的操作
false 组件将不会更新

  • 组件加载的时候触发的函数:

    constructor 、componentWillMount、 render 、componentDidMount

  • 组件数据更新的时候触发的生命周期函数:

    shouldComponentUpdate、componentWillUpdate、render、componentDidUpdate

  • 组件销毁的时候触发的:

    componentWillUnmount

发布了23 篇原创文章 · 获赞 2 · 访问量 1058

猜你喜欢

转载自blog.csdn.net/qq_45927123/article/details/103842788