react 基礎之組件篇三——設計複合組件
- 2019 年 11 月 13 日
- 筆記
設計複合組件
前言
你問我為什麼寫部落格? 因為阿拉斯加愛寫bugger!!!
微信公眾號:愛寫bugger的阿拉斯加 如有問題或建議,請往公眾號,我們一起交流如何寫bugger !
書接上文——react 基礎之組件篇二——Style in React 本節精彩繼續,阿拉斯加繼續裝逼如何優雅的寫bugger!!!
1. 複合組件要怎麼設計?
1.本節內容將實現如下效果,一個卡片。

卡片
分析
首先這個卡片可以分成三部分: 第一部分有背景色的內容分 第二部分是下面的描述部分 第三部分最大的盒子
- 直接在 style 裡面先定義好類名與樣式,組件上寫好對應的樣式名className 即可。
提醒: 設計組件時,一般都按照把控大局,再設計好每個小組件的規律。
第一部分程式碼如下:
var Square = React.createClass({ render: function() { var squareStyle = { height: 150, backgroundColor: this.props.color, textAlign: 'center', color: 'white', lineHeight:'150px' }; return ( <div style={squareStyle}> { this.props.content } </div> ); } });
第二部分程式碼如下:
var Label = React.createClass({ render: function() { var labelStyle = { fontFamily: "sans-serif", fontWeight: "bold", padding: 3, margin: 0, textAlign: 'center', }; return ( <div style={labelStyle}> <p>{ this.props.desc }</p> </div> ); } });
第三部分程式碼如下:
var Card = React.createClass({ render: function() { var cardStyle = { height: 200, width: 150, backgroundColor: "#FFF", WebkitFilter: "drop-shadow(0px 0px 5px #666)", filter: "drop-shadow(0px 0px 5px #666)" }; return ( <div style={cardStyle}> <Square color={this.props.color} content={this.props.content} /> <Label color={this.props.color} desc={this.props.desc}/> </div> ); } });
當然還有最後的調用如下:
ReactDOM.render( <div> <Card color="#FFA737" content="我是內容" desc="我是描述" /> </div>, destination );
效果如上圖卡片所示。 可以看到,不少值都是父組件 Card 通過 props 傳遞給 子組件Label和Square的,這樣子可以實現多種變化,不會定死只能是一個內容了,體現了組件的可擴展性。
4. 後語
雖然看上去很簡單,但是建議初學者自己敲一遍,可能會出現各種各樣的問題。學習,千萬不能有所見即所得的想法,實踐才是檢驗真理的唯一標準。
本節內容完畢!下節內容:「react 基礎之組件篇三」 將講解 設計複合組件。
原程式碼我都已經上傳到 github了,有興趣的可以去了解一下。
傳送門 https://github.com/biaochenxuying/react-learning