最近赶上项目react重构,正好也有点遗忘了...(bu hui le)趁这个机会来梳理一波把,后期关于redux,redux-saga,hook都会慢慢输出哈~路过的客官大老爷敬请指正哈
1、什么是JSX
一个JSX语法的示例,如下所示
const msg = 'world!'; const element = ( <h1>Hello, {msg}</h1> ); ReactDOM.render( element, document.getElementById('app') )
这种语法形式,既不是HTML,也不是字符串,而是称之为JSX,是React里用来描述UI和样式的语法,JSX最终会被编译为合法的JS语句调用(编译器在遇到{
时采用JS语法进行解析,遇到<
就采用HTML规则进行解析)
2、JSX实质
JSX通过babel编译,编译给React.createElement()调用。如下JSX代码:
const element = ( <h1 className='container'> Hello, world! </h1> );
等同于如下代码:
const element = React.creatElement( 'h1', {className: 'container'}, 'Hello, world!' )
React.createElement()方法会首先进行一些避免BUG的检查,然后返回类似以下例子的对象:
const element = { type: 'h1', props: { className: 'container', children: 'Hello, world!' } }
这样的对象,则称为react元素,代表所有呈现在屏幕上的东西。React正是通过读取这些对象来构建DOM,并且保持数据和UI同步的
3、渲染
在React中,使用ReactDOM.render()方法来将React元素渲染进一个DOM中。如:
ReactDOM.render( element, document.getElementById('app') )
4、组件和Props
组件(component)能够将UI划分为独立的、可复用的部分,这样我们就只需专注于构建每一个单独的部件。 从概念上看,组件就像是函数:接受任意的输入(称为属性,props),返回React元素。React中有两种定义组件的方式:函数定义和类定义
1、函数定义组件
function Welcome (props) { return <h1>Hello, {props.name}</h1>;; }
2、类定义组件
class Welcome extends React.Component { render () { return <h1>Hello, {this.props.name}<h1>; } }
3、组件渲染
上述定义了Welcome组件,并Welcome组件中声明了一个属性name,而这个属性将以props.name的方式传到组件内部,方法如下:
ReactDOM.render( <Welcome name="everybody" />, document.getElementById('root') )
最终就会以<h1>Hello everybody</h1>的方式呈现
5、State和生命周期
使用类定义组件有一些额外的好处,如拥有本地状态这一特性。 以下是一个类定义组件
class Clock extends React.Component { render () { return ( <div> <h1>Hello, world!</h1> <h2>Now is {this.props.date}</h2> </div> ); } }
需要注意的有:
· 类名即为组件名(无论是函数定义组件还是类定义组件,组件名称的首字母都必须大写,并且继承自React.Component)
· 使用 render() 方法,用来返回需要呈现的内容
1、在组件中使用State
state是属于一个组件自身的。我们可以在类的构造函数constructor中来初始化状态,如:
constructor (props) { super(props) this.state = { date: new Date() } }
这样一来便能在render方法中使用this.state.xxx
2、生命周期
React为我们提供了生命周期的钩子函数,方便我们进行使用。在React中,生命周期分为: 1、Mount 已插入真实DOM 2、Update 正在重新渲染 3、Unmount 已移出真实DOM 。生命周期钩子函数有:
componentWillMount componentDidMount componentWillUpdate componentDidUpdate componentWillUnmount //以下为特殊生命钩子函数 componentWillReceiveProps //已加载的组件收到新的参数时调动 shouldComponentUpdate // 组件判断是否重新渲染时调用
3、夜深了。。明天更~