从React开始

时间:2017-01-14 07:12:11

标签: javascript reactjs

我正在努力学习React。我正在使用React文档本身来学习。所以我试图在屏幕上渲染一个名为Comment的Component。但没有任何东西得到渲染。我也没有收到任何错误。

我正在使用文档本身提供的模板create-react-app来获取默认的反应应用程序,然后我用ReactDom.render()中的注释组件替换了默认的App组件。还有其他我应该做的事吗?

我在这做错了什么?

这些是我的代码:

的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')
);

1 个答案:

答案 0 :(得分: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')
);

我所做的只是将日期对象转换为Comment函数中的字符串。