一、高階組件就是一個函數,傳給它參數(包括組件,變量等),它返回一個新的組件javascript
二、列如如今有這麼個高階組件,根據傳入的參數name,從而從localstore中得到這個name的值,而後更新到傳入的參數component(組件)中去java
wrapWithLoadData.js文件的代碼:react
import Rect ,{component} from "react"app
export default (WrappedComponent,name)=>{ (WrappedComponent爲傳進來的組件,name爲傳進來的參數)函數
class NewComnent extends Component { //定一個組件來爲傳進來的組件進行數據處理學習
constructor(){this
super()spa
this.state={data:null}code
}component
componentWillMount(){
let data = localStorage.getItem(name)
this.setState({ data })
}
render () {
return <WrappedComponent data={this.state.data} />//高階組件內部的包裝組件和被包裝組件之間經過 props
傳遞數據。
}
}
return NewComponent //返回通過數據處理的組件(其實就是做爲參數傳進來的組件)
}
這就是一個高階組件,當某個組件要從localstore中獲值時,就能夠將這個組件做爲參數傳進來。
二、列:有一個組件InputWithUserName要用到上面的高階組件(即從localstore中獲取數據)
import wrapWithLoadData from './wrapWithLoadData' //得到高階組件
class InputWithUserName extends Component {
render () {
return <input value={this.props.data} />//高階組件內部的包裝組件和被包裝組件之間經過 props
傳遞數據。
}
}
InputWithUserName=wrapWithLoadData (InputWithUserName ,「username」)//將組件InputWithUserName做爲參數傳入高階組件,到高階組件中通過處理數據後再將其返回
export default InputWithUserName
三、如何用這個InputWithUserName組件
import InputWithUserName from './InputWithUserName'
class Index extends Component {
render () {
return ( <div> 用戶名:<InputWithUserName /> </div> )
}
}
別人用這個組件InputWithUserName的時候實際是用了被加工過的組件。
若是如今咱們須要另一個文本輸入框組件,它也須要 LocalStorage 加載'content'
字段的數據。咱們只須要定義一個新的 TextareaWithContent
:
import wrapWithLoadData from './wrapWithLoadData' class TextareaWithContent extends Component { render () { return <textarea value={this.props.data} /> } } TextareaWithContent = wrapWithLoadData(TextareaWithContent, 'content') export default TextareaWithContent
只用於本身學習記錄