1.子組件調用父組件的函數并傳遞數據(子傳父)
1.1父組件
import React, { Component } from 'react';
import ChildComponent from './ChildComponent';class ParentComponent extends Component {constructor(props) {super(props);this.state = {items: []};}// 父組件的方法,用于接收子組件傳遞的數據addList = (listObj) => {this.setState(prevState => ({items: [...prevState.items, listObj]}));};render() {return (<div><h2>Parent Component</h2><ChildComponent addList={this.addList} /><div><h3>Items:</h3><ul>{this.state.items.map((item, index) => (<li key={index}>{JSON.stringify(item)}</li>))}</ul></div></div>);}
}export default ParentComponent;
1.2子組件
import React, { Component } from 'react';class ChildComponent extends Component {handleAddItem = () => {// 創建要傳遞的對象const listObj = {id: Date.now(),name: `Item ${this.props.itemsCount || 0}`,value: Math.random()};// 調用父組件傳遞的函數并傳遞數據this.props.addList(listObj);};render() {return (<div><h3>Child Component</h3><button onClick={this.handleAddItem}>Add Item to Parent</button></div>);}
}export default ChildComponent;
1.3 總結?
- 父組件定義方法:父組件定義了一個 addList 方法,用于接收子組件傳遞的數據并更新狀態。
- 傳遞方法給子組件:父組件通過 props 將 addList 方法傳遞給子組件。
- 子組件調用父組件方法:子組件通過 this.props.addList(listObj) 調用父組件的方法,并傳遞數據。
- 狀態更新:父組件接收到數據后更新自己的狀態,觸發重新渲染。
2.父組件可以通過 props 直接向子組件傳遞數據(父傳子)?
2.1父組件
import React, { Component } from 'react';
import ChildComponent from './ChildComponent';class ParentComponent extends Component {constructor(props) {super(props);this.state = {list: [{ id: 1, name: 'Item 1' },{ id: 2, name: 'Item 2' },{ id: 3, name: 'Item 3' }]};}render() {return (<div><h2>Parent Component</h2>{/* 將 list 傳遞給子組件 */}<ChildComponent list={this.state.list} /></div>);}
}export default ParentComponent;
2.2子組件?
import React, { Component } from 'react';class ChildComponent extends Component {render() {// 從 props 中解構出 listconst { list } = this.props;return (<div><h3>Child Component</h3><ul>{list.map((item) => (<li key={item.id}>{item.name}</li>))}</ul></div>);}
}export default ChildComponent;
2.3 總結?
- 父組件傳遞數據:父組件通過 this.state.list 將數據傳遞給子組件。在 JSX 中,子組件的屬性被設置為 list={this.state.list}。
- 子組件接收數據:子組件通過 this.props.list 接收父組件傳遞的數據。在子組件的 render 方法中,使用解構賦值 const { list } = this.props; 來獲取 list。
- 渲染數據:子組件使用接收到的 list 數據來渲染一個無序列表。