zoukankan      html  css  js  c++  java
  • react-无状态组件

    import React, { Component } from "react";
    //import PostItem from "./PostItem";

    /**将无状态组件 嵌入 */

    function PostItem(props) {
    const handleClick = () => {
    props.onVote(props.post.id);
    };
    const { post } = props;
    return (
    <li>
    <div>{post.title}</div>
    <div>
    创建人:<span>{post.author}</span>
    </div>
    <div>
    创建时间:<span>{post.date}</span>
    </div>
    <div>
    <button onClick={handleClick}>点赞</button>
    &nbsp;
    <span>{post.vote}</span>
    </div>
    </li>
    );
    }

    //export default PostItem

    class PostList extends Component {
    constructor(props) {
    super(props);
    this.state = {
    posts: []
    };
    this.timer = null;
    this.handleVote = this.handleVote.bind(this); //ES6 class 中 必须手动绑定this
    }

    //render 后
    componentDidMount() {
    // 用setTimeout模拟异步从服务器端获取数据
    this.timer = setTimeout(() => {
    this.setState({
    posts: [
    {
    id: 1,
    title: "大家一起来讨论React吧",
    author: "张三",
    date: "2017-09-01 10:00",
    vote: 0
    },
    {
    id: 2,
    title: "前端框架,你最爱哪一个",
    author: "李四",
    date: "2017-09-01 12:00",
    vote: 0
    },
    {
    id: 3,
    title: "Web App的时代已经到来",
    author: "王五",
    date: "2017-09-01 14:00",
    vote: 0
    }
    ]
    });
    }, 1000);
    }

    componentWillUnmount() {
    if (this.timer) {
    clearTimeout(this.timer);
    }
    }

    handleVote(id) {
    //根据帖子id进行过滤,找到待修改vote属性的帖子,返回新的posts对象
    const posts = this.state.posts.map(item => {
    const newItem = item.id === id ? { ...item, vote: ++item.vote } : item;
    return newItem;
    });
    this.setState({
    posts
    });
    }

    render() {
    return (
    <div>
    帖子列表
    <ul>
    {this.state.posts.map(item => (
    <PostItem post={item} onVote={this.handleVote} />
    ))}
    </ul>
    </div>
    );
    }
    }
    export default PostList;
  • 相关阅读:
    sublime & atom 插件
    正则表达式必知必会读书笔记
    前端自动化工具
    CSS3效果收集
    JS 常用功能收集
    【1】Hover 效果收集
    javascript进阶高手必备知识
    ionic 实现仿苹果手机通讯录搜索功能
    ionic2APP 如何处理返回键问题
    三张图搞懂JavaScript的原型对象与原型链
  • 原文地址:https://www.cnblogs.com/iOS-mt/p/10296440.html
Copyright © 2011-2022 走看看