2015-10-18 84 views
1

我需要将所有React组件解析为它们各自的React元素(例如,type = div,ul,li),包括可能存在的所有嵌套组件。我已经成功地做到了;不过,我收到了关于直接调用React组件的警告。另外,我很可能会首先解决错误。如何将嵌套的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); 
} 
+0

我不知道我明白你在这里做什么;这个问题可能是[XY问题](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。但警告是因为你调用'.type'作为一个函数,而不是调用'React.createElement(type,...)' –

+0

@BinaryMuse,但是'React.createElement(type,...)'不实际上让孩子们接触到这个组件,这正是我所需要的。它们是隐藏的,只能在函数调用中访问。如果您有更好的方法,可能只需解决此问题。 – jedmao

+0

你有没有想过这个?我试图为我正在编写的序列化反应组件的库... reactElement.type(reactElement.props)显示警告,但不会为我返回值。 :( –

回答

0

原始代码现在返回一个错误在0.14.7,没有输出,从反应,(如上面提供的链接描述再次,行为)包含用于警告相同的消息。

更新你的代码这一点,因为每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,看起来可能有帮助,我需要进行试验。

这有点荒谬,这是多么困难。我不确定在这一点上我错过了什么架构决策。