reactjs父子組件間的傳值


父傳子數據  props

FatherComponent.jsx

image

image

image

ChildComponent.jsx

image

父傳子方法 props

FatherComponent.jsx

image

image

ChildComponent.jsx

image

帶參數的方法:

FatherComponent.jsx

image

image

ChildComponent.jsx

image

image

父組件將自身傳給子組件 props

FatherComponent.jsx

image

image

image

ChildComponent.jsx

image

父組件獲取子組件的數據 refs

FatherComponent.jsx

image

image

image

ChildComponent.jsx

image

父組件獲取子組件的方法 refs

FatherComponent.jsx

image

image

ChildComponent.jsx

image

image

帶有參數的方法:

FatherComponent.jsx

image

image

image

ChildComponent.jsx

image

注意:ref綁定的ChildComponent必須是一個class組件,不能是個函數組件。因為React會給class創建組件實例,而不會給函數組件創建實例,你因此可以發現函數組件里沒有用this進行實例屬性定義。同時ref也可以綁定在普通的標簽上面,所以證明了this.refs只是個普通對象,他既可以保存dom元素,也可以保存React組件的實例對象(class組件)

補充

官方實際已經不推薦使用字符串形式的ref(有問題,未來可能刪除這個API),而是推薦使用回調ref。

即ref的值是一個回調函數,回調函數有一個element參數,element就是綁有ref屬性的dom。

【上面介紹的通過ref來進行父子組件通訊,基本使用沒有改變,只是把ref的綁定值進行了更改。】(不再通過this.refs來獲取ref綁定的dom)

下面以表單text來進行演示:

image

進行化簡后:

image

或者你還可以通過官方新增的API(React.createRef()),來使用ref (個人感覺這種最好理解)

image

與回調ref略微不同,獲取dom是通過 this.textInput.current

你還可以通過props和ref結合使用,來獲取多次嵌套的子組件中的標簽元素,詳細做法自行思考。

其實就是通過props把回調函數或者是ref對象(React.createRef())傳遞下去。

組件的defaultProps和propTypes

defaultProps:用來初始化組件的props屬性

ChildComponent.jsx

image

當父組件FatherComponent沒有給子組件ChildComponent的props屬性傳遞message參數值時,會使用default值 => message:’這里是默認信息’

如果有傳,則會覆蓋掉default值。

propTypes:對組件props屬性中的值進行類型約束  (is propTypes no prototype)

ChildComponent.jsx

先導入react的依賴模塊prop-types

image

image

這里對子組件ChildComponent的props屬性中的message進行類型約束,message必須是個string,如果不是string則會報錯


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM