在 React 中,父子组件之间的渲染可以通过两种方法实现:
// 父组件
function ParentComponent() {
const data = 'Hello World';
return <ChildComponent data={data} />;
}
// 子组件
function ChildComponent(props) {
return <div>{props.data}</div>;
}
// 父组件
class ParentComponent extends React.Component {
static childContextTypes = {
data: PropTypes.string
};
getChildContext() {
return {
data: 'Hello World'
};
}
render() {
return <ChildComponent />;
}
}
// 子组件
class ChildComponent extends React.Component {
static contextTypes = {
data: PropTypes.string
};
render() {
return <div>{this.context.data}</div>;
}
}
以上是两种常用的父子组件渲染方法,开发者可以根据具体需求选择合适的方法。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: react异步请求数据的方法是什么