react 组件封装原则_我理解的React:React 到底是什么?
最近要做一個“前端零基礎的入門課程分享”,很多非前端同學可能只是知道 React 是個前端框架,整體對 React 的理解還是很模糊,借此機會,分享一下我對 React 的理解。
最重要的寫在前面
React是一個前端UI庫。我對React的理解主要就兩點:
在React基礎上,周邊生態(tài)提供了更多強大功能:狀態(tài)管理、路由、React Native等。
一、組件化
這里就有了第一個抽象概念:?組件?。
什么是組件?組件是對邏輯的封裝。對于前端 UI 層來說,組件就是將 UI 封裝起來。供任意組裝和調(diào)用。太抽象了?我提煉成三個點,幫助大家理解:
最簡單的組件 HelloWorld
下面我們看一個最簡單的類組件 HelloWorld:
// HelloWorld.jsx class HelloWorld extends React.Component {componentDidMount () {console.log('HelloWorld 第一次掛載到界面上');}componentWillUnmount () {console.log('HelloWorld 即將移除(銷毀)');}render() {return (<div>Hello World!</div>);} }這樣就完成了一個簡單的 ?HelloWorld? 組件。
子組件調(diào)用示例
再寫一個 按鈕組件 ?HelloButton?
// HelloButton.jsx class HelloButton extends React.Component {render() {return (<button>我是一個按鈕</button>);} }寫一個父組件 把 HelloWorld 和 HelloButton 兩個組件包裹進來
// Wrap.jsx class Wrap extends React.Component {render() {return (<div><HelloWorld></HelloWorld><HelloButton></HelloButton></div>);} }可以看到 React 調(diào)用子組件其實就是把子組件當做一個標簽,跟 div 這些標簽一樣。
Wrap 組件最終的展示就是,一個HelloWord 組件 + 一個HelloButton 組件,如下圖。
Wrap組件效果圖組件化小結
基于對組件化的理解:寫 React 就是寫一個個組件,再組裝起來。所以如果用分治的思想,我們只要關注每個組件怎么實現(xiàn)就好了。
二、數(shù)據(jù)驅動
現(xiàn)在來講我的另一個理解——?數(shù)據(jù)驅動?,那么組件有哪些數(shù)據(jù)呢?
組件有兩種數(shù)據(jù):父組件傳遞的參數(shù) Props和組件內(nèi)部的狀態(tài)State,先來分別看一個例子。
組件的狀態(tài) State
先來看效果:
組件 State 示例,效果圖完整代碼如下:
// App.jsx class App extends React.Component {constructor () {super()this.state = {count: 0}}onIncrease = () => {this.setState({ count: this.state.count + 1 })}onDecrease = () => {this.setState({ count: this.state.count - 1 })}render() {return (<div><div>當前數(shù)值:{this.state.count}</div><button onClick={this.onIncrease}>點我-1</button><button onClick={this.onDecrease}>點我+1</button></div>);} }解析:
建議沒看到上面例子的同學,帶著上面的解析,重新嘗試能否看懂。
上面的例子中,?count? 就是 App組件 的一個 State
父組件傳遞的屬性 Props
從語義上理解:Props 是父組件傳遞給子組件的屬性,與 State 不同的是子組件不能修改,只有父組件才能修改。
先看看如何使用 Props:
// HelloMessage.jsx class HelloMessage extends React.Component {render() {return (<div><div>Hello {this.props.username}</div></div>);} }上述例子,使用的示例、效果如下:
<HelloMessage username="秦書羽" />
Props 使用效果圖解析:子組件在使用Props時,使用 ?this.props? 直接調(diào)用即可,父組件在使用子組件時,應將需要的數(shù)據(jù)傳給子組件。
數(shù)據(jù)驅動的理解
上面兩個例子中,界面都是根據(jù)數(shù)據(jù)來渲染,且隨著數(shù)據(jù)變化,自動更新,這就是數(shù)據(jù)驅動渲染。
再說下數(shù)據(jù)驅動的理解:
從這個方面去理解,React 是一個 Model -> View 的一個框架。
“數(shù)據(jù)驅動”的理解圖數(shù)據(jù)驅動模式帶來的收益
個人見解:
三、總結
字節(jié)跳動杭州游戲中臺急招Web前端(實習、P5-P6(1-5 年) 都要),新業(yè)務,發(fā)展好。歡迎簡歷 qinshuyu@bytedance.com,部門直推。職位JD(僅供參考)
感謝您的閱讀,歡迎評論區(qū)指正、交流。
總結
以上是生活随笔為你收集整理的react 组件封装原则_我理解的React:React 到底是什么?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: vs2015卸载指南
 - 下一篇: 可变数据(VDP)软件 数码印刷和传统印