由於公司是外包性質,項目老是vue框架和react框架交替着開發,導致開發一段時間vue又把react的東西忘記了,反之亦然。所以在這里記錄下react的開發簡要,方便以后查詢。
腳手架相關
react采用的是自己開發的腳手架:create-react-app,全局安裝,然后鍵入dos命令:create-react-app (項目文件夾) 即可初始化react腳手架項目包,但是注意下載源和npm版本
過低都會造成依賴模塊丟失或者下載不了的問題,建議源切換為國外的。這里推薦一款npm下載源管理的工具: nrm(具體使用方法:https://www.npmjs.com/package/nrm)
es6相關
由於項目大部分都是采用es6~es7語法開發了,react關於es6的語法 : https://babeljs.io/blog/2015/06/07/react-on-es6-plus,兼容性就找babel-polyfill吧
react入門相關
react中的組件分為普通組件和容器組件(我理解為業務組件),普通組件只負責簡單的數據渲染,不做邏輯處理,最簡單的組件可以這樣寫:
1 // 這樣就相當於一個普通組件了 2 const Test = (props) => <div>測試組件</div> 3 4 export default class Main extends Component { 5 render () { 6 return ( 7 <Test></Test> 8 ) 9 } 10 }
容器組件一般的結構:
1 // 容器組件 2 export default class Main extends Component { 3 // 構造函數 4 constructor (props) { 5 super(props) 6 7 // 初始化組件數據 8 this.state = {} 9 } 10 11 // 默認傳值 12 static defaultProps: {} 13 14 // 生命周期 15 // 請求數據 16 componentDidMount () {} 17 18 // 事件數據 19 handleSome () {} 20 21 // 渲染 22 render () { 23 return ( 24 <Test></Test> 25 ) 26 } 27 28 }
跟着說react開發中要注意的地方:
1.jsx是一種js的擴展語法,可以理解為具有模板能力和js所有功能的組。JSX 表達式就變成了常規的 JavaScript 對象,Babel將jsx編譯的例子:
1 const element = ( 2 <h1 className="greeting"> 3 Hello, world! 4 </h1> 5 ); 6 7 const element = React.createElement( 8 'h1', 9 {className: 'greeting'}, 10 'Hello, world!' 11 ); 12 13 /** 14 * <h1 className="greeting"> 15 * Hello, world! 16 * </h1> 17 * 這樣的模板片段等同於 18 */ 19 const element = { 20 type: 'h1', 21 props: { 22 className: 'greeting', 23 children: 'Hello, world' 24 } 25 };
2.this.props.children
這個東西我的理解為一個插槽,在組件傳值的時候,容器組件包含的組件。
3.獲取dom,和vue的$refs索引一個用法,做個備忘
4.proptypes校驗props,是否必須存在,為什么類型
但是react15.5版本之后,proptypes成為了一個單獨的模塊,所以要先下載依賴 prop-types再去使用
1 // PropTypes用於驗證props的傳值 2 Test.propTypes = { 3 name: Proptypes.string.isRequired 4 }
5.關於react的列表渲染
react的列表渲染,必須向子組件傳遞一個key的props。官方的解釋是:React 使用這個 key 去比較原來的樹的子節點和之后樹的子節點。我的理解為,方便dom的索引,提高渲染效率,如果沒有這個key則會去比較兩棵dom樹。
注:key的聲明必須在使用組件的時候
1 // key的取值一般為數據中的索引值index 2 const numbers = [1, 2, 3, 4, 5]; 3 const listItems = numbers.map((number, index) => 4 <li key={index}> 5 {number} 6 </li> 7 );
6.利用context進行越級組件傳遞props
使用context可以獲取到祖先元素中的數據,避免多層傳遞的麻煩。
1 // 祖先組件 2 class Parent extends Component { 3 getChildContext () { 4 return { 5 text: '祖先組件中的文本' 6 } 7 } 8 9 render () { 10 const Parent = this 11 return ( 12 <div> 13 <ContextTest></ContextTest> 14 </div> 15 ) 16 } 17 } 18 19 Parent.childContextTypes = { 20 text: Proptypes.string 21 } 22 23 // 中間件 24 const ContextTest = (props) => { 25 return ( 26 <div> 27 <Child></Child> 28 </div> 29 ) 30 } 31 32 // 底層組件 33 // class Child extends Component { 34 // render () { 35 // return ( 36 // <div> 37 // {this.context.text} 38 // </div> 39 // ) 40 // } 41 // } 42 43 const Child = (props, context) => { 44 return ( 45 <div> 46 {context.text} 47 </div> 48 ) 49 } 50 51 Child.contextTypes = { 52 text: Proptypes.string.isRequired 53 }