如何将嵌套的React组件解析为元素树?

时间:2015-10-18 08:55:04

标签: reactjs

我需要将所有React组件解析为各自的React元素(例如,type = div,ul,li),包括可能存在的所有嵌套组件。我已经成功地做到了;但是,我收到关于直接调用React组件的警告。而且,我很可能一开始就错了。

function resolveNestedDomElements(reactElement) {
    // is there a better way to check if it's a component?
    if (React.isValidElement(reactElement) && _.isFunction(reactElement.type)) {
        // is there a better way to access a component's children?
        reactElement = reactElement.type(reactElement.props);
        // Warning: Something is calling a React component directly. Use a
        // factory or JSX instead. See https://fb.me/react-legacyfactory
        // Note: Unfortunately, the factory solution doesn't work.
    }
    if (!React.isValidElement(reactElement)) {
        return reactElement;
    }
    let { children } = reactElement.props;
    if (React.Children.count(children)) {
        if (React.isValidElement(children)) {
            children = resolveNestedDomElements(children);
        } else {
            children = React.Children.map(
                children,
                resolveNestedDomElements
            );
        }
    }
    return React.cloneElement(reactElement, reactElement.props, children);
}

1 个答案:

答案 0 :(得分:0)

您的原始代码现在返回0.14.7中的错误,没有来自React的输出,包含用于警告的相同消息(同样,上面提供的链接中描述的行为)。

根据the update here更新您的代码:

    function resolveNestedDomElements(reactElement) {
        if (React.isValidElement(reactElement) && typeof reactElement.type === 'function') {
            reactClass = React.createFactory(reactElement.type)
            reactElement = reactClass(Object.assign({},reactElement.props));
            }
        if (!React.isValidElement(reactElement)) {
            return reactElement;
        }
        let { children } = reactElement.props;
        if (React.Children.count(children)) {
            if (React.isValidElement(children)) {
                children = resolveNestedDomElements(children);
            } else {
                children = React.Children.map(
                    children,
                    resolveNestedDomElements
                );
            }
        }
        return React.cloneElement(reactElement, reactElement.props, children);
    }

这不再警告(或者,在当前版本中,它现在只返回您发布的原始形式的错误),但输出也未解决。我不清楚为什么会发生这种变化。

答案似乎是似乎无法再解决了。我不能完全遵循React源代码中发生的事情(我相信组件的渲染函数最终会被ReactDOM.render调用,但是我的工作原理还不清楚)。调用ReactDOM.render并不能在没有DOM的情况下工作。有一个react-test-utils.shallowRenderer看起来可能有用,我需要进行试验。

这有多么困难,这有点荒谬。我不确定此时我缺少什么样的架构决策。