【React】类组件和函数组件

构建组件的方式

  1. 函数式组件(function)
  2. createElement(不建议使用)
  3. 类组件形式创建(不建议使用)

对于 React 的理解

React, 用于构建用户界面的JavaScript库,本身只提供了Ul层面的解决方案。(遵循组件设计模式、声明式编程范式和函数式编程概念,以使前端应用程序更高效。)

使用虚拟D0M来有效地操作DOM,遵循从高阶组件到低阶组件的单向数据流。帮助我们将界面成了各个独立的小块,每一个块就是组件,这些组件之间可以组合、嵌套,构成整体页面,且易于理解和增加可维护性。

比如类组件,jsx 会被 babel 编译为合法的 js 语句。被传入的数据可以通过 this.props 在 render() 中访问。

js 复制代码
class HelloMessage extends React.Component {
    render() {
        return <div>Hello {this.props.name}</div>;
    }
}
ReactDOM.render(
    <HelloMessage name="Taylor" />,
    document.getElementById("hello-example")
);

react 还有一些特性,jsx 语法、单向数据流(react 本身来说 props 只能通过父组件向子组件传输,不能反过来修改,便于对数据的控制)、虚拟 DOM(diff、patch,高效操作 DOM)、声明式编程、Component(一切皆为组件)

声明式编程:关注要做什么,而不是怎么做,我们可以根据逻辑的计算声明要显示的组件。

比如命令式编程,一步一步描述过程进行操作:

js 复制代码
const map = new Map.map(document.getElementById("map"), {
    zoom: 4,
    center: { lat, lng },
});

const marker = new Map.marker({
    position: { lat, lng },
    title: "Hello Marker",
});

marker.setMap(map);

然后 react 的声明式编程只需要,声明出页面结构,然后渲染页面:

js 复制代码
<Map zoom={4} center={(lat, lng)}>
    <Marker position={(lat, lng)} title={"Hello Marker"} />
</Map>

state 和 props

state 用于维护自身组件的数据状态,setState 用于修改这个数据状态,进行更新组件,重新调用组件的 render 方法;props 用来接收外部(单向数据流流,所以一般是父组件)传过来的数据(在子组件内为不可变的)。

js 复制代码
class Button extends React.Component {
    constructor() {
        super();
        this.state = {
            count: 0,
        };
    }
    updateCount() {
        this.setState((prevState, props) => {
            return { count: prevState.count + 1 };
        });
    }
    render() {
        return (
            <button onClick={() => this.updateCount()}>
                Clicked {this.state.count} times
            </button>
        );
    }
}

setState 还可以接受第二个参数,它是一个函数,会在setState调用完成并且组件重新渲染之后被调用,可以用来监听渲染是否完成:

js 复制代码
this.setState(
    {
        name: "JS ",
    },
    () => console.log("setState finished")
);

super() 和 super(props) 的区别

super 代表父类的构造函数,子类没有自己的 this,只能继承父类的 this 作为自己的 this,所以 super 的调用必须在constructor 的第一行 。调用 this ,一般需要传入 props 作为参数,如果不手动传入,react 内部也会自动传入 props 。所有无论有没有 constructor ,render 中都是可以调用 this.props 的。

使用 super(name) 相当于调用 father.prototype.constructor.call(this.name)

但是也不建议使用super()代替super(props)。因为在 React会在类组件构造函数生成实例后再给 this.props赋值,所以在不传递 props在 super的情况下,调用 this.props 为undefined,如下情况:

js 复制代码
class Button extends React.Component {
    constructor(props) {
        super(); // props
        console.log(props); // {}
        console.log(this.props); // undefined
        // ...
    }
}

而传入props的则都能正常访问,确保了this.props在构造函数执行完毕之前已被赋值,更符合罗辑,如下:

js 复制代码
class Button extends React.Component {
    constructor(props) {
        super(props); // props
        console.log(props); // {}
        console.log(this.props); // {}
        // ...
    }
}

对于类组件和函数组件的理解

  1. 写法不同
  2. 状态管理(setState 、 useState)
  3. 生命周期(函数组件不存在生命周期,它是使用 useEffect 替代生命周期发挥作用)
  4. 调用方法(函数直接调用,类实例化后再调用render方法)
  5. 获取渲染的值

props 是只读的,但是 this 是可变的(可以在 render 和生命周期读取最新值),所以如果组件在请求运行时更新,类组件 this.props 可以获取最新的值,而 函数组件 props 仍是旧值(函数组件本身不存在 this)。

js 复制代码
// function
function ProfilePage(props) {
    const showMessage = () => {
        alert('Followed ' + props.user);
    }
    const handleClick = () => {
        setTimeout(showMessage, 3000);
    }
    return (
        <button onClick={handleClick}>Follow</button>
    )
}
// class
class ProfilePage extends React.Component {
    showMessage() {
        alert('Followed ' + this.props.user);
    }
    handleClick() {
        setTimeout(this.showMessage.bind(this), 3000);
    }
    render() {
        return <button onClick={this.handleClick.bind(this)}>Follow</button>
    }
}
相关推荐
烟雨国度1 小时前
双向数据绑定原理图
前端·javascript·vue.js
GISer_Jing1 小时前
React速成
前端·javascript·react.js
李元中1 小时前
2024下半年软考中级软件设计师,这100题,必做!
java·开发语言·javascript·人工智能·算法·ecmascript
敏编程3 小时前
网页前端开发之Javascript入门篇(9/9):对象
开发语言·javascript
太阳花ˉ4 小时前
html+css+js实现Collapse 折叠面板
javascript·css·html
曹天骄4 小时前
React 组件命名规范
前端·javascript
..undefined4 小时前
JavaScript 基础 && 高级
javascript
陆仟4 小时前
正则表达式【JavaScript】
javascript·正则表达式
Jiaberrr5 小时前
微信小程序实战教程:如何使用map组件实现地图功能
前端·javascript·微信小程序·小程序·map