Skip to content
This repository has been archived by the owner on Jun 2, 2022. It is now read-only.

三:组件及其生命周期 #4

Open
ivanberry opened this issue Feb 23, 2018 · 0 comments
Open

三:组件及其生命周期 #4

ivanberry opened this issue Feb 23, 2018 · 0 comments
Assignees
Labels
React基础知识 关于React的基础知识点
Milestone

Comments

@ivanberry
Copy link
Owner

ivanberry commented Feb 23, 2018

应用组成

元素

元素是React应用最基本的单元,可用来构建组件,继而形成应用。我们都知道DOM中元素的任何操作都是高代价的。而在React Dom中,元素就是最基本的对象数据结构。

const element = <h1>Hello, world</h1>

这就是一个最简单的元素了。

通过ReactDom就可以渲染到浏览器中,成为真实的Dom元素:

<div id="root"></div>
const element = <h1>Hello, world.</h1>
ReactDOM.render(element, document.getElementById('root'));

借由ReactDom的render方法,我们就能将元素渲染到浏览器中,成为浏览器中的真实节点。另外须提到,元素是不可变的,也就是说我们不能在已有元素上添加或者修改某些属性,我们只能完全替换,这里可类别电影的制作,是连续的帧构成了连续的状态。同理,是不同时刻下不同的状态的元素,串成了可变的应用状态。

何为组件?

要说元素构成了组件,那么组件就是构成React应用的基本单元。

React组件按照不同的分类有多重分类,不过就前期学习而言,我们先只要建立只有一种组件的概念就好,囫囵吞枣可能会噎着。

React是非常彻底的组件化开发应用,它的官网就有很显著的描述:

Component-based

Build encapsulated components that manage their own state, then compose them to make complex UIs.

Since component logic is written in JavaScript instead of templates, you can easily pass rich data through your app and keep state out of the DOM.

依然跟上一章一致,我们通过在线的形式先认识清楚React的嘴脸:

React在线玩耍地址

React组件可以类比为乐高玩具,不同作用的乐高模块可以用来建立高楼大厦的不同功能部分,而我们不同的组件,就是用来构建React应用的不同UI组成一样。但是它们可能存在这么一个区别:React组件可能不是一蹴而就的,是在迭代过程中,发现,某一部分可以成为组件。

从概念上看,组件和JavaScript函数一样,你的输入(props)决定它看起来像什么。

//simplest component
function Welcome(props) {
    return <h1>Hello, world.</h1>
}

class Welcome extends React.Component {
    render() {
        return <h1>Hello, world.</h1>
    }
}

两种不同的组件书写方法,对React而言是基本一致,对开发者而言存在一定的差距,后面我们将提及。

组件的渲染

function Welcome(props) {
    return <h1>Hello, {props.name}</h1>
}

const element = <Welcome name='Sara' />
ReactDOM.render(
	element,
	document.getElementById('root')
);

从代码上简单组件的渲染时极其简单的,无非就是创建-->插入-->渲染的过程而已。组件的运营等不属于React的基本知识,什么时候需要组合,拆分组件是实践出来的。

All React components must act like pure functions with respect to their props.

灵活的React库有以上这一条严格的准则,大白话讲就是:组件本身任何情况下不得修改props。但是应用本身基本是动态的,那如何来使得应用动态化呢?state,呼之欲出。

@ivanberry ivanberry added the React基础知识 关于React的基础知识点 label Feb 23, 2018
@ivanberry ivanberry added this to the React Baisc milestone Feb 23, 2018
@ivanberry ivanberry self-assigned this Feb 23, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
React基础知识 关于React的基础知识点
Projects
None yet
Development

No branches or pull requests

1 participant