当前位置: 首页 > React学习笔记 > 正文
流量卡

React组件基础

游魂 发表于2022年6月15日 11:15

React 组件介绍

组件允许你将 UI 拆分为独立可复用的代码片段,并对每个片段进行独立构思。

组件表示页面中的部分功能,组合多个组件实现完整的页面。

功能特点:可复用、独立、可组合。

React组件的两种创建方式

React 创建组件方法:

  1. 使用函数 function
  2. 使用类 class

函数组件

1)什么是函数组件?

2)定义函数组件

// 普通函数
function Header() {
  return <div>头部组件</div>;
}

// 箭头函数
const Footer = () => {
  return <div>底部组件</div>;
};

// 不渲染内容
const Loading = () => {
  const loading = false;
  return loading ? <div>正在加载...</div> : null;
};

3)使用组件

import ReactDom from 'react-dom';

// 普通函数
function Header() {
  return <div>头部组件</div>;
}

// 箭头函数
const Footer = () => {
  return <div>底部组件</div>;
};

// 加载组件,不渲染内容
const Loading = () => {
  const loading = false;
  return loading ? <div>正在加载...</div> : null;
};

// 根组件
const App = () => {
  return (
    <>
      <Header />
      <Loading />
      <Footer />
    </>
  );
};

ReactDom.render(<App />, document.getElementById('root'));

总结

类组件

class 语法

复习一下定义class、定义属性、定义函数。

// 动物
class Animal {
  address = '地球';
  eat() {
    console.log('吃');
  }
}

extends 继承父类

// 猫
class Cat extends Animal {
  run() {
    console.log('跑');
  }
}

const cat = new Cat();
cat.run(); // 跑
cat.eat(); // 吃
console.log(cat.address); // 地球

总结: class创建类,extends继承类,可以使用父类的属性和函数。

1)什么是类组件?

2)定义类组件

import { Component } from 'react';

class Header extends Component {
  render() {
    return <div>头部组件</div>;
  }
}

3)使用类组件

import { Component } from 'react';
import ReactDom from 'react-dom';

// 头部
class Header extends Component {
  render() {
    return <div>头部组件</div>;
  }
}

// 根组件
class App extends Component {
  render() {
    return (
      <>
        <Header />
      </>
    );
  }
}

ReactDom.render(<App />, document.getElementById('root'));

总结

组件抽离

如果所有组件写在一个文件,代码写在一起后续会难以维护,组件作为一个独立的个体,一般都会放到一个单独的JS文件中。

抽离组件

具体操作:

1.新建 src/components/Header.jsx 类组件,新建 src/components/Footer.jsx 函数组件

import { Component } from 'react';
class Header extends Component {
  render() {
    return <div>头部组件</div>;
  }
}
export default Header;
const Footer = () => {
  return <div>底部组件</div>;
};
export default Footer;

2.新建 src/App.jsx 组件, 导入Header Footer组件使用。

import { Component } from 'react';
import Header from './components/Header.jsx';
import Footer from './components/Footer.jsx';
class App extends Component {
  render() {
    return (
      <>
        <Header />
        内容
        <Footer />
      </>
    );
  }
}

3.index.js 使用 App 根组件

import ReactDom from 'react-dom';
import App from './App.jsx';
ReactDom.render(<App />, document.getElementById('root'));

无状态组件和有状态组件

简单理解:

无状态(函数)组件,负责静态结构展示

有状态(类)组件,负责更新UI,让页面动起来

1.无状态组件

2.有状态组件

3.它们的区别

4.如何去选择

总结

类组件 - 定义状态

import { Component } from 'react';

class App extends Component {
  // 状态
  state = {
    title: '数码产品',
    list: ['电脑', '手机', '相机'],
  };
  render() {
    return (
      <>
        <h3>{this.state.title}</h3>
        <ul>
          {this.state.list.map((item) => {
            return <li key={item}>{item}</li>;
          })}
        </ul>
      </>
    );
  }
}
export default App;

总结:

类组件 - 绑定事件

import { Component } from 'react';

class App extends Component {
  // 状态
  state = {
    count: 0,
  };
  // 事件处理函数
  handleClick(e) {
    // 默认行为
    e.preventDefault();
    // 事件冒泡
    e.stopPropagation();
    console.log('handleClick');
  }
  handleMouseEnter() {
    console.log('handleMouseEnter');
  }
  render() {
    return (
      <>
        <div onMouseEnter={this.handleMouseEnter}>
          计数器:{this.state.count}
        </div>
        <div>
          <a href="http://www.iyouhun.com" onClick={this.handleClick}>
            按钮
          </a>
        </div>
      </>
    );
  }
}
export default App;

总结:

事件绑定this指向

1.发现this是undefined

import { Component } from 'react';

class App extends Component {
  // 状态
  state = {
    count: 0,
  };
  // 事件处理函数
  handleClick(e) {
    console.log(e);
    // Uncaught TypeError: Cannot read properties of undefined (reading 'state')
    console.log(this.state.count);
  }
  render() {
    return (
      <>
        <div>计数器:{this.state.count}</div>
        <div>
          <button onClick={this.handleClick}>按钮</button>
        </div>
      </>
    );
  }
}
export default App;

2.演示处理函数调用对 this 的影响

const obj = {
  name: 'tom',
  say() {
    console.log(this);
  },
};
obj.say(); // 打印:{name: 'tom', say: function}
const say = obj.say;
say(); // 打印:window对象  严格模式

3.问题原因

处理 this 指向问题

1.通过绑定箭头函数解决 this 问题

import { Component } from "react";

class App extends Component {
  // 状态
  state = {
    count: 0,
  };
  // 事件处理函数
  handleClick(e) {
    console.log(e)
    console.log(this.state.count)
  }
  render() {
    return (
      <>
        <div>计数器:{this.state.count}</div>
        <div>
+          <button onClick={(e)=>this.handleClick(e)}>按钮</button>
        </div>
      </>
    );
  }
}
export default App;

2.通过 bind 解决 this 问题

import { Component } from "react";

class App extends Component {
  // 状态
  state = {
    count: 0,
  };
  // 事件处理函数
  handleClick(e) {
    console.log(e)
    console.log(this.state.count)
  }
  render() {
    return (
      <>
        <div>计数器:{this.state.count}</div>
        <div>
+          <button onClick={this.handleClick.bind(this)}>按钮</button>
        </div>
      </>
    );
  }
}
export default App;

3.通过声明箭头函数解决 this 问题(推荐)

利用箭头函数形式的class实例方法。

注意:该语法是实验性语法,但是,由于babel的存在可以直接使用。

import { Component } from "react";

class App extends Component {
  // 状态
  state = {
    count: 0,
  };
  // 事件处理函数
+  handleClick = (e) => {
    console.log(e)
    console.log(this.state.count)
  }
  render() {
    return (
      <>
        <div>计数器:{this.state.count}</div>
        <div>
          <button onClick={this.handleClick}>按钮</button>
        </div>
      </>
    );
  }
}
export default App;

类组件 - setState 使用

1.通过setState的来修改数据更新视图

import { Component } from 'react';

class App extends Component {
  state = {
    count: 0,
  };
  handleClick = () => {
    // 修改数据
    this.setState({
      // key是要修改的数据名称,value是对应的新值
      count: this.state.count + 1,
    });
  };
  render() {
    return (
      <>
        <div>计数器:{this.state.count}</div>
        <div>
          <button onClick={this.handleClick}>按钮</button>
        </div>
      </>
    );
  }
}
export default App;

2.修改数组和修改对象的正确姿势

import { Component } from 'react';

class App extends Component {
  state = {
    count: 0,
    user: {
      name: 'jack',
      age: 18,
    },
    list: ['电脑', '手机'],
  };
  handleClick = () => {
    // 修改数据
    this.setState({
      // key是要修改的数据名称,value是对应的新值
      count: this.state.count + 1,
    });
  };
  updateList = () => {
    // 修改列表
    this.setState({
      list: [...this.state.list, '相机'],
    });
  };
  updateUser = () => {
    // 修改对象
    this.setState({
      user: {
        ...this.state.user,
        name: 'tony',
      },
    });
  };
  render() {
    return (
      <>
        <div>计数器:{this.state.count}</div>
        <div>
          <button onClick={this.handleClick}>按钮</button>
        </div>
        <hr />
        <div>商品:{this.state.list.join(',')}</div>
        <button onClick={this.updateList}>改数组</button>
        <hr />
        <div>
          姓名:{this.state.user.name},年龄:{this.state.user.age}
        </div>
        <button onClick={this.updateUser}>改对象</button>
      </>
    );
  }
}
export default App;

类组件 - 受控组件

1.什么是受控组件

import { Component } from 'react';

class App extends Component {
  state = {
    mobile: '13811112222',
    isAgree: true,
  };

  changeMobile = (e) => {
    this.setState({
      mobile: e.target.value,
    });
  };

  changeAgree = (e) => {
    this.setState({
      isAgree: e.target.checked,
    });
  };

  render() {
    return (
      <>
        <div>
          <input
            value={this.state.mobile}
            onChange={this.changeMobile}
            type="text"
            placeholder="请输入手机号"
          />
        </div>
        <div>
          <input
            checked={this.state.isAgree}
            onChange={this.changeAgree}
            type="checkbox"
          />
          同意用户协议和隐私条款
        </div>
      </>
    );
  }
}
export default App;

总结:

类组件 - 非受控组件

1.什么是非受控组件?

2.通过 ref 获取表单元素获取非受控组件的值

import { Component, createRef } from 'react';

class App extends Component {
  // 获取非受控组件的值
  // 1. 通过createRef创建一个ref对象
  // 2. 给元素绑定ref属性值为创建的ref对象
  // 3. 通过ref对象的current获取元素,再获取它的值
  mobileRef = createRef();

  getMobile = () => {
    console.log(this.mobileRef.current.value);
  };

  render() {
    return (
      <>
        <div>
          {/* 没有被state控制的表单原生认为是非受控组件 */}
          <input ref={this.mobileRef} type="text" placeholder="请输入手机号" />
          <button onClick={this.getMobile}>获取</button>
        </div>
      </>
    );
  }
}
export default App;

总结:

总结

1.组件的两种创建方式:函数组件和类组件

2.无状态(函数)组件,负责静态结构展示

3.有状态(类)组件,负责更新UI,让页面动起来

4.绑定事件注意this指向问题

5.推荐使用受控组件来处理表单

6.完全利用JS语言的能力创建组件,这是 React的思想

全文完
本文标签: React组件React组件基础React组件学习React定义组件
本文标题: React组件基础
本文链接: https://www.iyouhun.com/m/?post=223

〓 随机文章推荐

共有1475阅 / 0我要评论
  1. 还没有评论呢,快抢沙发~

发表你的评论吧返回顶部

!评论内容需包含中文

请勾选本项再提交评论