2017-03-12

// Code goes here

class Product extends React.Component{
  constructor(props){
    super(props);
    this.state={
      qty:0,
    }
    this.buy = this.buy.bind(this);
    this.show = this.show.bind(this);
  }

  buy(){
    this.setState({
      qty:this.state.qty+1
    });
    this.props.handleCalculate(this.props.price);
  }

  show(){
    this.props.handleShow(this.props.name);
  }

  render(){
    return(
      <div>
        <p>{this.props.name} - ${this.props.price}</p>
        <button onClick={this.buy}>buy</button>
        <button onClick={this.show}>show</button>
        <h3>{this.state.qty}</h3>
        <hr/>
      </div>
      );
  }
}

class Total extends React.Component{
  render(){
    return(
      <div>Total cost: {this.props.total}</div>
    );
  };
}

class ProductForm extends React.Component{
  constructor(props){
    super(props);
    this.submit = this.submit.bind(this);
  }
  submit(e){
    e.preventDefault();
    //alert("name: " + this.refs.name.value + "="+this.refs.price.value)
    var product = {
      name: this.refs.name.value,
      price: parseInt(this.refs.price.value) || 0,
    }

    this.props.handleCreate(product);
    this.refs.name.value="";
    this.refs.price.value="";
  }

  render(){
    return(
      <form>
        <input type="text" placeholder="Product name" ref="name" />
        <input type="text" placeholder="Product price" ref="price" />
        <button onClick={this.submit}>submit</button>
      </form>
    );
  }
}

class ProductList extends React.Component{
  constructor(props){
    super(props);
    this.state={
      total:0,
      productList: [
        {name:"Android", price:12},
        {name:"Apple", price:23},
        {name:"Samsung", price:45},
      ],
    }
    this.calculate = this.calculate.bind(this);
  }

  calculate(price){
    this.setState({
      total: this.state.total+price
    });
  }

  showProduct(name){
    alert('you select'+name);
  }

  createProduct(product){
    this.setState({
      productList: this.state.productList.concat(product)
    })
  }

  render(){
    var component = this;
    var products = this.state.productList.map(function(product){
      return(
        <Product name={product.name} price={product.price} handleShow={component.showProduct}
                 handleCalculate={component.calculate}/>
      );
    })
    return(
      <div>
        <ProductForm handleCreate={this.createProduct.bind(this)}/>
        {products}
        <Total total={this.state.total}/>
      </div>
    );
  };
}


var rootElement = document.getElementById('root');

ReactDOM.render(
  <ProductList />, rootElement
);

오랜만에 리액트해보니 재밌다.

results matching ""

    No results matching ""