import React from 'react';
class Blog extends Component {
render(){
const sidebar = (
<ul>
{this.props.posts.map((post) =>
<li key={post.id}>
{post.title}
</li>
)}
</ul>
);
const content = this.props.posts.map((post) =>
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.content}</p>
</div>
);
return (
<div>
{sidebar}
<hr />
{content}
</div>
);
}
}
const posts = [
{id: 1, title: 'Hello World', content: 'Welcome to learning React!'},
{id: 2, title: 'Installation', content: 'You can install React from npm.'}
];
ReactDOM.render(
<Blog posts={posts} />,
document.getElementById('root')
);
请帮助我摆脱这个错误。我只是一个初学者。其实这个程序写的功能。作为学习的一部分,我试图改变课堂上的写作。但不幸的是我没有得到输出。是否可以在类中添加键?
答案 0 :(得分:0)
您的代码存在两个问题: 你忘了从反应中导入'组件'。 你忘了从react-dom导入'ReactDOM'。
尝试以下代码,它将起作用:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
class Blog extends Component {
render(){
const sidebar = (
<ul>
{this.props.posts.map((post) =>
<li key={post.id}>
{post.title}
</li>
)}
</ul>
);
const content = this.props.posts.map((post) =>
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.content}</p>
</div>
);
return (
<div>
{sidebar}
<hr />
{content}
</div>
);
}
}
const posts = [
{id: 1, title: 'Hello World', content: 'Welcome to learning React!'},
{id: 2, title: 'Installation', content: 'You can install React from npm.'}
];
ReactDOM.render(
<Blog posts={posts} />,
document.getElementById('root')
);
答案 1 :(得分:0)
您的代码在逻辑上看起来很好。但可能存在以下问题。
class Blog extends Component
组件来自哪里,尝试通过编写class Blog extends React.Component