React组件是如何工作的?
React 组件是任何 React 应用的基本构建模块。它们允许我们将复杂的 UI 分解成小块,从而简化 UI 的运行。
但正如以往一样,任何抽象都有其代价, React 组件的概念本身就让很多初学者感到困惑,所以让我们来弄清楚吧!
React 组件 vs React 组件实例 vs React 元素
这三个术语看似指的是同一件事——屏幕上的用户界面元素。但事实并非如此。
React 组件
React 组件要么是一个函数,要么是一个 ES6 类——仅此而已。你可以在这里管理状态、处理事件并实现其他自定义逻辑。
它本身不会渲染任何内容到屏幕上。渲染操作需要你创建它的实例来完成。
const TextButton = ({text}) => {
return <button>{text}</button>;
}
// It becomes more obvious with class-based component
// because you extend React.Component, not React.Element
class ListItem extends React.Component {
render() {
return <li>{this.props.children}</li>;
}
}
React 组件实例
顾名思义,React 组件可能只在运行时存在一个实例。此外,也可能存在多个实例,每个实例都有自己的属性和本地状态。这种情况会在多次
使用React 组件时发生。
class ListItem extends React.Component {
constructor(props) {
super(props);
console.log(`This is instance ${this}`);
}
render() {
return <li>{this.props.children}</li>;
}
}
const App = () => {
return (
<ul>
<ListItem>First item</ListItem>
<ListItem>Second item</ListItem>
<ListItem>Third item</ListItem>
</ul>
);
}
React Element
React Element是React Component Instance在运行时返回的对象。它是一个普通的 JavaScript 对象,完整地描述了一个 DOM 节点。
多个React Element共同构成一个虚拟 DOM,这是一个树状结构,用于描述 React 应用的 UI。
// After Babel
const App = () => {
return React.createElement('ul', null,
React.createElement(ListItem, {children: 'First item'}),
React.createElement(ListItem, {children: 'Second item'}),
React.createElement(ListItem, {children: 'Third item'})
)
}
// At run-time
const App = () => {
return {
"type": "ul",
"key": null,
"ref": null,
"props": {
"children": [
{
"type": class ListItem,
"key": null,
"ref": null,
"props": {
"children": "First item"
},
},
// ...
]
}
}
}
React 组件工作原理概览
- React 开发者创建基于函数或基于类的React 组件,这些组件返回 JSX。
- Babel在构建时将 JSX 转译为 .jsx
React.createElement()或 .jsx 。jsx() - React在运行时创建必要的React 组件实例,它们返回React 元素。
ReactDOM渲染由React 元素组成的虚拟 DOM 。
PS:今天就到这里啦!关注我的推特账号,获取更多内容!
文章来源:https://dev.to/fromaline/how-react-components-work-520f