2017-01-13 126 views
0

我有測試組件,我想用它在ShowTest作爲渲染一個組件到另一個

import React from "react"; 

export default class Test extends React.Component{ 
    render() { 
     return (
      <div>hi test</div> 

     ); 

    } 
} 

我渲染測試,以ShowTest如下

import {Test} from "./test"; 
import React from "react"; 
export default class ShowTest extends React.Component{ 
    render() { 
     return (
      <div> 
      <Test /> 
      </div> 

     ); 

    } 
} 

然後我使用ShowTest到另一個零件。
但我收到此錯誤

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined 

無法弄清楚爲什麼發生這種情況。

+0

沒有你在'ShowTest'組件進口'Test'? – nrgwsth

+0

**你是如何導入'Test'的? [可能有關?](http://stackoverflow.com/questions/34130539/uncaught-error-invariant-violation-element-type-is-invalid-expected-a-string)(抱歉,首先編輯是錯誤的鏈接) – Hodrobond

+3

嘗試從「./test」導入測試' – Hodrobond

回答

1

它看起來像您的Test組件輸入的語法是錯誤的。

由於您已將Test導出爲默認設置,因此導入ShowTest時不需要大括號。

import {Test} from "./test"; 

應該

import Test from "./test"; 
+0

大括號的含義是什麼?我總是在使用或不使用時感到困惑。 –

+1

大括號用於[解構賦值](https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring)。 你基本上是導出一個對象。 'default'爲整個對象提供一個名字,但是名爲exports的內容是一個名字,可以直接導出和導入,而不必導入整個模塊。您可以在同一個文件中同時執行兩個命名導出_和_默認導出。 – jaybee

0

雙重檢查,但在兩個單獨的文件中是兩個組件?

如果它們都在同一個文件中,則語法關閉,因爲聲明export default class name extends React.Component時只能有一個默認值。

如果它們在兩個單獨的文件中,請仔細檢查它們是否都有可能是錯誤原因的import React from "react"。另一個可能導致錯誤的問題是組件未被包含,因此不知道是什麼。

+0

這兩個組件在不同的文件與導入React和ShowTest呈現正確。但測試是給出錯誤 –

+0

正如其他答案中所述,導入測試組件的註釋應該是'import Test從「./test」開始。 大括號不需要,並導致您的示例的錯誤。 – Gary