You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用React顶层API构建父组件并运行时注入子组件(非JSX实现)

React 无JSX等价实现方案

JSX本质是React.createElement顶层API的语法糖,你给出的JSX代码可以直接用该API实现等价效果,示例如下:

render() {
    const { trowserOpen, item ,organizer, requestId, intl, onClose } = this.props;

    // 1. 先构造Child组件的实例,运行时可动态替换为其他组件实现注入效果
    const childNode = React.createElement(Child, {
        item: item,
        organizer: organizer,
        requestId: requestId,
        onClose: onClose
    });

    // 2. 构造Parent组件实例,将Child作为子元素传入
    return React.createElement(Parent, {
        autoFocus: true,
        history: false,
        onClose: this.handleCloseTrowser,
        open: trowserOpen,
        title: intl.formatMessage({ id: 'trowserTitle' }),
        dismissible: true
    }, childNode);
}

注意事项

  • JSX中不带赋值的布尔属性(如autoFocus、dismissible)默认值为true,在createElement的props参数中需要显式赋值
  • 你通过script标签加载React时,React为全局对象,可直接调用createElement方法,无需额外引入
  • 要实现运行时动态注入组件,只需要根据业务逻辑动态调整传入Parent的第三个参数即可,比如根据状态判断传入Child、其他组件或者null
  • 如果存在多个子元素,可在第三个参数位置依次传入多个元素,或者直接传入子元素数组

内容的提问来源于stack exchange,提问作者Deepak Krishnan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 22:39:03