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;
  • 相关阅读:
    计算机网络基础,子网掩码,网络号,子网号,主机号主机数量计算方式
    Nginx配置大全与搭建手册
    Windows10仿mac-os主题
    kali-linux知识整理与渗透测试指南
    简单的钓鱼网站制作-Setoolkit
    渗透测试常用工具-Metasploit_常用模块
    提权方式及原理简介(面试)
    修改dedecms精简版
    内网存活主机探测的一些方法
    免杀测试
  • 原文地址:https://www.cnblogs.com/iOS-mt/p/10296440.html
Copyright © 2011-2022 走看看