React:如何在页面层级为嵌套组件设置自定义prop值
解决方案
方案1:Props透传(适合固定布局场景)
这种方案不用修改现有子组件逻辑,只需要调整TextImage组件,把上层传入的参数转发给内部嵌套的Text和Image组件即可,既能保留复用性,也能给每个复用的实例传入不同属性:
- 修改
TextImage.js代码:
import React from 'react'; import { Container, Row, Col } from 'react-bootstrap'; import Text from '../Text/Text'; import Image from '../Image/Image'; import "./TextImage.scss"; class TextImage extends React.Component{ render(){ // 提取上层传入的所有子组件需要的属性 const { header, copy, image_src, image_alt } = this.props; return( <section className="textImage"> <Container> <Row> <Col md={6}> <Text header={header} copy={copy} /> </Col> <Col md={6}> <Image image_src={image_src} image_alt={image_alt} /> </Col> </Row> </Container> </section> ) } } export default TextImage;
- 在
Homepage.js中直接传入属性复用:
import React from "react"; import TextImage from "../components/TextImage/TextImage"; function Homepage() { return ( <> {/* 复用多份,每份传入不同参数互不影响 */} <TextImage header="首页头部标题" copy="首页头部对应的文本说明" image_src="/home-banner.jpg" image_alt="首页banner图" /> <TextImage header="产品介绍标题" copy="产品对应的功能说明文本" image_src="/product.jpg" image_alt="产品展示图" /> </> ); } export default Homepage;
如果后续子组件的属性增多,也可以把同类属性封装成对象,用解构展开简化透传代码,比如把Text需要的所有属性放在textProps对象中,透传时写为<Text {...this.props.textProps} />即可。
方案2:Children插槽(适合高灵活度场景)
如果后续需要调整子组件的顺序、新增自定义内容,可以用插槽方案,让TextImage只负责布局外壳,具体内容由上层传入:
- 修改
TextImage.js代码:
import React from 'react'; import { Container, Row } from 'react-bootstrap'; import "./TextImage.scss"; class TextImage extends React.Component{ render(){ return( <section className="textImage"> <Container> <Row> {/* 直接渲染上层传入的子元素 */} {this.props.children} </Row> </Container> </section> ) } } export default TextImage;
- 在
Homepage.js中自定义内容:
import React from "react"; import { Col } from 'react-bootstrap'; import Text from "../components/Text/Text"; import Image from "../components/Image/Image"; import TextImage from "../components/TextImage/TextImage"; function Homepage() { return ( <> <TextImage> <Col md={6}> <Text header="标题" copy="文本内容" /> </Col> <Col md={6}> <Image image_src="/img.jpg" image_alt="图片说明" /> </Col> </TextImage> </> ); } export default Homepage;
内容的提问来源于stack exchange,提问作者Freddy
相关产品推荐
相关产品推荐

