reactjs - 如何以编程方式创建 react 组件的实例?

标签 reactjs components instantiation

我有一个表行组件,用于检查是否指定了自定义组件,是否应该以编程方式获取该 React 组件 (column.customComponent) 并使用它呈现数据。但是,我似乎无法实例化组件。我得到的只是字符串形式的数据。

这是我的:

const cellContent = typeof(column.customComponent === 'undefined') ?
  rowData[column.columnName] :
  {
    type: column.customComponent,
    props: {
      data: rowData[column.columnName],
      rowData
    }
  };

console.log(cellContent); 显示如下内容: the function representation of the React component 或者 函数 DateCell() ....

我不确定我是否只是在使用 wrong syntax在分配 cellContent 时,或者我是否应该与工厂一起做某事时。 我应该怎么做?

最佳答案

我使用这个辅助方法来创建组件并返回实例。

static async renderComponentAt(componentClass, props, parentElementId){
         let componentId = props.id;
        if(!componentId){
            throw Error('Component has no id property. Please include id:"...xyz..." to component properties.');
        }

        let parentElement = document.getElementById(parentElementId);

        return await new Promise((resolve, reject) => {
            props.ref = (component)=>{
                if(component){
                    resolve(component);
                }                    
            };
            let element = React.createElement(componentClass, props, null);
            ReactDOM.render(element, parentElement);
        });
    } 

关于reactjs - 如何以编程方式创建 react 组件的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37604594/

相关文章:

java - 从另一个java类访问组件

reactjs - 如何在react-table中添加不区分大小写的过滤组件内容?

javascript - React-Native 'Cannot add a child that doesn' t 有一个 YogaNode 到没有测量功能的 parent !

reactjs - 如何使用 React 获取 Azure 广告刷新 token

reactjs - 请向我解释一下这个奇怪的 React 语法

javascript - 当 Formik 表单更改时更新另一个组件

oop - 在 MATLAB 中根据名称实例化类

javascript - 如何有条件地为组件设置 onClick 属性,而不必重复嵌套代码行?

java - 在Java中以更简洁的方式实例化 map

c++ - 模板类的模板构造函数的实例化