在學習 React 框架組件間數據傳輸知識點前,我們需要先明確幾點使用原則。
- React的組件間通訊是單向的。數據必須是由父級傳到子級或者子級傳遞給父級層層傳遞。
- 如果要給兄弟級的組件傳遞數據,那么就要先傳遞給公共的父級而后在傳遞給你要傳遞到的組件位置。
- 這種非父子關系的組件間傳遞數據,不推薦使用這種層層傳遞的方式;而是選擇使用維護全局狀態功能模塊(Redux)
一、父組件向子組件傳遞數據
父組件向子組件傳遞數據是通過在父組件中引用子組件時,在子組件標簽設置傳輸數據的屬性;而子組件中通過 this.props 接受傳過來的數據;這樣就實現了父組件向子組件的數據傳輸。
1.1、父組件代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
import React, { Component } from 'react' ; import './App.css' ; import Child from './child' class App extends Component { constructor(props){ super (props); this .state={ msg: '父類的消息' , name: 'John' , age:99 } } callback=(msg,name,age)=>{ // setState方法,修改msg的值,值是由child里面傳過來的 this .setState({msg}); this .setState({name}); this .setState({age}); } render() { return ( <div className= "App" > <p> Message: { this .state.msg}</p> <Child callback={ this .callback} age={ this .state.age} name={ this .state.name}></Child> </div> ); } } export default App; |
代碼說明:父組件在使用子組件(Child)的過程中,對子組件傳輸了兩個屬性(age和name)和一個方法(callback 先不考慮)。
關鍵代碼:
1
|
< Child name={this.state.name} age={this.state.age}></ Child > |
1.2、子組件代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import React from "react" ; class Child extends React.Component{ constructor(props){ super (props); this .state={ name: 'Andy' , age:31, msg: "來自子類的消息" } } change=()=>{ this .props.callback( this .state.msg, this .state.name, this .state.age); } render(){ return ( <div> <div>{ this .props.name}</div> <div>{ this .props.age}</div> <button onClick={ this .change}>點擊</button> </div> ) } } export default Child; |
代碼說明:子組件中在 render 中直接使用 this.props 接受父組件傳輸的數據,并直接使用。不推薦子組件將接受到的數據,再使用this.setSate 方式處理。
關鍵代碼:
1
2
|
< div >{this.props.name}</ div > < div >{this.props.age}</ div > |
二、子組件向父組件傳輸數據
React 框架中子組件向父組件傳輸數據,要依賴于父組件向子組件傳輸數據。實際上就是父組件將自己作用域的函數傳輸給子組件;子組件調用該函數,并將要傳輸的數據,通過函數的參數的形式,傳輸給父組件。
2.1、父組件代碼
上面的代碼示例中,父組件中定義了函數,并將這個函數傳輸給了子組件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class App extends Component { ...... callback=(msg,name,age)=>{ // setState方法,修改msg的值,值是由child里面傳過來的 this .setState({msg}); this .setState({name}); this .setState({age}); } render() { return ( <div className= "App" > <Child callback={ this .callback}></Child> </div> ); } } export default App; |
父組件將自己作用域的函數傳遞給子組件,子組件在通過 this.props
調用此函數的過程中,通過參數的方式將數據傳輸到組組件中。
這里父組件有三個形參:msg,name,age;子組件將數據傳輸過來后,父組件會將其使用 this.setState
方式處理。
2.2、子組件代碼
子組件通過使用 this.props 接受到父組件傳輸過來的函數;并調用此函數通過參數的方法,傳輸數據給父組件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class Child extends React.Component{ ...... change=()=>{ this .props.callback( this .state.msg, this .state.name, this .state.age); } render(){ return ( <div> <button onClick={ this .change}>點擊</button> </div> ) } } export default Child; |
子組件中創建了一個方法 change()
,此方法和點擊事件 onClick
綁定;change()
方法中會調用 this.props.callback()
函數(父組件傳輸過來的函數);函數的實參就是子組件傳輸給父組件的數據。
以上就是詳解React 父組件和子組件的數據傳輸的詳細內容,更多關于React 父組件和子組件的數據傳輸的資料請關注服務器之家其它相關文章!
原文鏈接:https://cn-blogs.cn/archives/9701.html