.
3ss.cn

react创建组件的三种方式是什样

下面是react创建组件的三种方式及特点,希望能够对大家有所帮助。

1、函数式组件:

(1)语法:

function myConponent(props) {
	return `Hello${props.name}`
}

(2)特点:

新增了hooks的API可以去官网了解下,以前是无状态组件,现在是可以有状态的了

组件不能访问this对象

不能访问生命周期方法

(3)建议:

如果可能,尽量使用无状态组件,保持简洁和无状态。【笔者的意思就是尽量用父组件去操控子组件,子组件用来展示,父组件负责逻辑】

2、es5方式React.createClass组件

(1)语法:

var myCreate = React.createClass({
	defaultProps: {
		//code
	},
	getInitialState: function() {
		return { //code };
	},
	render:function(){
		return ( //code );
	}
})

(2)特点:

这种方式比较陈旧,慢慢会被淘汰

(免费视频教程推荐:javascript视频教程)

3、es6方式class:

(1)语法:

class InputControlES6 extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			state_exam: props.exam
		}
		//ES6类中函数必须手动绑定
		this.handleChange = this.handleChange.bind(this);
	}
	handleChange() {
		this.setState({
			state_exam: 'hello world'
		});
	}
	render() {
		return( //code )
	};
}

(2)特点:

成员函数不会自动绑定this,需要开发者手动绑定,否则this不能获取当前组件实例对象。

状态state是在constructor中初始化

props属性类型和组件默认属性作为组建类的属性,不是组件实例的属性,所以使用类的静态性配置。

请朋友们瑾记创建组件的基本原则:

组件名首字母要大写

组件只能包含一个根节点(如果这个根节点你不想要标签将它包住的话可以引入Fragment,Fragment不会用没关系,可以观看笔者的react基础知识整理(1)

尽量使用函数式组件,保持简洁和无状态。

最后我们对比一下函数组件和class组件对于一个相同功能的写法差距:

由父组件控制状态的对比

函数组件:

function App(props) {
	function handleClick() {
		props.dispatch({ type: 'app/create' });
	}
	return <div onClick={handleClick}>{props.name}</div>
}

class组件:

class App extends React.Component {
	handleClick() {
		this.props.dispatch({ type: 'app/create' });
	}
	render() {
		return <div onClick={this.handleClick.bind(this)}>{this.props.name}</div>
	}
}

自己维护状态的对比

import React, { useState } from 'react';
function App(props) {
	const [count, setCount] = useState(0);
	function handleClick() {
		setCount(count + 1);
	}
	return <div onClick={handleClick}>{count}</div>
}

class组件:

class App extends React.Component {
	state = { count: 0 }
	handleClick() {
		this.setState({ count: this.state.count +1 })
	}
	render() {
		return <div onClick={this.handleClick.bind(this)}>{this.state.count}</div>
	}
}
赞(0)
未经允许不得转载:互联学术 » react创建组件的三种方式是什样

评论 抢沙发