一、初级react程序1
//index.js
import React from 'react';
import ReactDOM from 'react-dom';
import PostList from './PostList';
ReactDOM.render(<PostList />, document.getElementById('root'));
//PostList.js
import React,{Component} from 'react'
class PostList extends Component {
render() {
return (
<div>
帖子列表:
<ul>
<li>大家一起来讨论React吧</li>
<li>前端框架,你喜欢吗?</li>
<li>Web App的时代已经到来</li>
</ul>
</div>
);
}
}
export default PostList;
结果:
二、初级react程序2
//index.js 同“一、初级react程序1”
//PostItem.js
import React,{Component} from 'react'
class PostItem extends Component {
render(){
const{title,author,date} = this.props;
return (
<li>
<div>
{title}
</div>
<div>
创建人:<span>{author}</span>
</div>
<div>
创建时间:<span>{date}</span>
</div>
</li>
);
}
}
export default PostItem;
//PostList.js
import React,{Component} from 'react'
import PostItem from './PostItem'
//真实项目中,帖子列表数据一般从服务器获取
const data =[
{title:'大家一起来讨论React吧',author:'张三',date:'2020-03-12 09:43'},
{title:'前端框架,你喜欢吗?',author:'李四',date:'2020-03-12 09:44'},
{title:'Web App的时代已经到来',author:'王五',date:'2020-03-12 09:45'}
];
class PostList extends Component {
render() {
return (
<div>
帖子列表:
<ul>
{data.map(item =>
<PostItem title={item.title} author={item.author} date={item.date}/>)}
</ul>
</div>
);
}
}
export default PostList;
结果:
三、初级react程序3
//index.js 同“一、初级react程序1”
//PostList.js 同“二、初级react程序2”
//PostItem.js
import React,{Component} from 'react'
import { render } from 'react-dom';
class PostItem extends Component{
constructor(props){
super(props);
this.state = {
vote:0
};
}
//处理点赞逻辑
handleClick() {
let vote = this.state.vote;
vote++;
this.setState({
vote:vote
});
}
render(){
const{title,author,date} = this.props;
return (
<li>
<div>
{title}
</div>
<div>
创建人:<span>{author}</span>
</div>
<div>
创建时间:<span>{date}</span>
</div>
<div>
<button onClick={()=>{this.handleClick();}}>点赞</button>
<span>{this.state.vote}</span>
</div>
</li>
);
}
}
export default PostItem;
结果: