2017-01-24 84 views
0

望着在ReactJS文檔的"Choosing the Type at Runtime" section,它看起來像下面的代碼應該工作:ReactJS無效的組件類型

class App extends Component { 
    constructor() { 
    super(); 

    this.state = { test: <div>Test</div>}; 
    } 

    render() { 
    const Test = this.state.test; 

    return <Test />; 
    } 
} 

但是,沒有渲染,並在控制檯中我看到了以下錯誤:

warning.js:36 Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of `App`. 

我不明白爲什麼這不起作用;請解釋。

請注意,上述測試應用程序是使用create-react-app創建的。

回答

2

這會創建一個元素 - 要渲染到屏幕的DOM節點的特定實例。

this.state = { test: <div>Test</div>}; 

這需要該元素,並試圖把它當作一個成分 - 一個作出反應函數或類,它知道如何將自己呈現爲一個元素。

const Test = this.state.test; 
return <Test />; 

要使用從傳統的面向對象的比喻,這將是類似於拍攝一類實例並試圖使用它作爲一個類。

像這樣的東西應該工作,而不是:

this.state = { test: <div>Test</div>}; 
// ... 
return this.state.test; 

欲瞭解更多信息,請參閱"React Components, Elements, and Instances."