2015-10-18 81 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,看起來可能有幫助,我需要進行試驗。

這有點荒謬,這是多麼困難。我不確定在這一點上我錯過了什麼架構決策。