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 中解构出 list
const { 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 数据来渲染一个无序列表。