fullstack react(一)第一个react应用

import React from 'react'
import ReactDom from 'react-dom'

const products = [
  {id:'1',scores:30,title:'title1',content:'content1 is here'},
  {id:'2',scores:13,title:'title2',content:'content2 is here'},
  {id:'3',scores:20,title:'title3',content:'content3 is here'},
  {id:'4',scores:322,title:'title4',content:'content4 is here'},
]



class Product extends React.Component{
  constructor(props){
    super(props);
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick(e){
    e.preventDefault();
    this.props.handleProductClick(this.props.id)

  }

  render(){
    return(
      <div border='1'>
        <a onClick={this.handleClick}>
          赞{this.props.score}
        </a>
        <h2>{this.props.title}</h2>
        <p>{this.props.content}</p>
        <hr/>
      </div>
    );
  }
}

class ProductList extends React.Component{

  constructor(props){
    super(props);
    this.state={
      products:[]
    }
    this.handleClickProductScore = this.handleClickProductScore.bind(this)
  }

  componentDidMount(){
    this.setState({
      products:products
    })

  }

  handleClickProductScore(id){
    console.log(id)
    const productList = this.state.products.map(product=>{
      if(product.id===id){
        return Object.assign({},product,{scores:product.scores+1});
      }else{
        return product;
      }
    })

    this.setState({
      products:productList
    })
  }


  render(){
    const productlist = Object.assign([],this.state.products)
    productlist.sort((a,b) => b.scores-a.scores)
    const sortedProductList = productlist.map(
      product=>(<Product
        key={product.id}
        id={product.id}
        score={product.scores}
        title={Product.title}
        content={product.content}
        handleProductClick={this.handleClickProductScore}
    />)
    )
    return(
      <div>
        {sortedProductList}
      </div>
    );
  }
}


ReactDom.render(
  <ProductList />,
  document.getElementById('root')
)

  

posted @ 2018-08-05 09:12  tutu_python  阅读(81)  评论(0)    收藏  举报