React TypeScript自定义组件如何捕获并渲染内部子元素?
React组件如何接收并渲染内部子元素?
你现在的问题是调用组件时传入了内部元素,但组件没渲染它,这是因为React默认会把组件标签包裹的所有内容放到props.children属性里,你只需要在组件中接收并渲染这个属性就行,具体步骤如下:
1. 修正组件语法并添加子元素渲染逻辑
原组件代码存在TypeScript写法错误(比如函数组件定义格式、多余的render方法),同时需要加入props.children的渲染逻辑,修正后的代码如下:
import React, { FunctionComponent } from 'react'; interface ComponentProps { message: string; // 可选:显式声明children类型,不声明也能正常使用,因为FunctionComponent默认包含该属性 children?: React.ReactNode; } export const MyComponent: FunctionComponent<ComponentProps> = (props) => { return ( <div> {props.message} {/* 在这里渲染传入的内部子元素 */} {props.children} </div> ); };
2. 调用组件验证效果
你原来的调用方式不需要修改,现在组件会同时渲染message内容和传入的内部div:
<MyComponent message='Test'> <div>How to render this div inside MyComponent, how to catch it?</div> </MyComponent>
补充说明
props.children可以接收任意类型的React节点:单个元素、多个元素、文本、甚至是渲染回调函数- 如果不需要显式声明
children属性,也能直接在组件中使用props.children,因为FunctionComponent的泛型默认包含children?: React.ReactNode的定义
内容的提问来源于stack exchange,提问作者Alnedru
相关产品推荐
相关产品推荐

