2017-01-14 106 views
1

我在努力學習React。我正在使用React文檔來學習。所以我試圖在屏幕上渲染一個名爲Comment的Component。但是沒有任何東西被渲染。我也沒有得到任何錯誤。以React開頭

我使用文檔本身提供的模板create-react-app來獲取默認反應應用程序,然後用ReactDom.render()中的評論組件替換默認應用程序組件。還有什麼我應該做的?

我在做什麼錯在這裏?

這是我的代碼:

的index.html:

<!doctype html> 

<html lang="en"> 
    <head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> 
    <title>React App</title> 
    </head> 
    <body> 
    <div id="root"></div> 

    </body> 
</html> 

我的js文件

import React from 'react'; 
import ReactDOM from 'react-dom'; 

function Comment(props) { 
    return (
     <div className="Comment"> 
      <div className="UserInfo"> 
       <img 
        src={props.author.imgUrl} 
        alt={props.author.name} 
       /> 
       <div className="UserInfo-name"> 
        {props.author.name} 
       </div> 
      </div> 
      <div className="Comment-text"> 
       {props.text} 
      </div> 
      <div className="Comment-date"> 
       {props.date} 
      </div> 
     </div> 
    ); 
} 

const comment = { 
    date: new Date(), 
    text: 'I hope you enjoy learning React!', 
    author: { 
     name: 'Hello Kitty', 
     imgUrl: 'http://placekitten.com/g/64/64' 
    } 
}; 

ReactDOM.render(
    <Comment 
     author={comment.author} 
     text={comment.text} 
     date={comment.date} 
    />, 
    document.getElementById('root') 
); 
+0

你的HTML看起來像什麼?你的HTML中有一個id爲'root'的元素嗎? – thedayturns

+0

我已將它添加到問題 – leoOrion

+0

你沒有在你的HTML文件中包含你的JS文件;-) – thedayturns

回答

1

這似乎解決您的問題:

function Comment(props) { 
    return (
     <div className="Comment"> 
      <div className="UserInfo"> 
       <img 
        src={props.author.imgUrl} 
        alt={props.author.name} 
       /> 
       <div className="UserInfo-name"> 
        {props.author.name} 
       </div> 
      </div> 
      <div className="Comment-text"> 
       {props.text} 
      </div> 
      <div className="Comment-date"> 
       {props.date.toString()} 
      </div> 
     </div> 
    ); 
} 

const comment = { 
    date: new Date(), 
    text: 'I hope you enjoy learning React!', 
    author: { 
     name: 'Hello Kitty', 
     imgUrl: 'http://placekitten.com/g/64/64' 
    } 
}; 

ReactDOM.render(
    <Comment 
     author={comment.author} 
     text={comment.text} 
     date={comment.date} 
    />, 
    document.getElementById('root') 
); 

所有我確實是把日期的目標ct轉換成Comment函數中的字符串。

+0

謝謝..它的工作。但是爲什麼其他信息沒有出現?還是錯誤? – leoOrion

+3

P.S.我發現它的日期對象是我在JSX的部分內容中註釋掉了,直到我找到了一些工作,然後逐個添加回來,直到我找出JSX的哪一部分導致問題。調試應用程序通常是一個很好的策略。 :) – thedayturns

+0

感謝您的提示 – leoOrion