React 官网例子实现一个列表

官网参考地址:https://reactjs.org/docs/thinking-in-react.html

学习了react的quicksart部分之后跟着官网的文档进行一次react的开发探索。

首先是实现的效果:

React 官网例子实现一个列表_第1张图片

功能描述:能够输入关键字进行模糊查询,点击复选框只显示黑色字体部分。

下面是实现的过程,首先分析整个页面,如何把一个功能模块进行合理的拆分成一个个小的功能模块。

React 官网例子实现一个列表_第2张图片

searcbar:搜索组件

productCategoryrow:类别行组建

productRow:具体的商品数据列表

productTable:所有的table

FilterTableProductTable:所有功能的父组件

具体的代码如下:

Demo.js

import React from 'react';
import ReactDOM from 'react-dom';

/**
 * 行类别
 */
class ProductCategoryRow extends React.Component{
    render (){
        const category = this.props.category;
        return (
            
                
                    {category}
                
            
        );
    }
}

/**
 * 行数据
 */
class ProductRow extends React.Component{
    render(){
        const product = this.props.product;
        const name = product.stocked?
            product.name:
            
                {product.name}
            ; 
        return (
            
                {name}
                {product.price}
            
        );
    }
}

/**
 * 数据的表格
 */
class ProductTable extends React.Component{
    render(){
        const filterText = this.props.filterText;
        const inStockOnly = this.props.inStockOnly;

        const rows = [];
        let lastCategory = null;

        this.props.products.forEach((product) => {
            // 检查是否有相同
            if(product.name.indexOf(filterText)===-1){
                return;
            }
            if(inStockOnly && !product.stocked){
                return;
            }

            // 大类别
            if(product.category!==lastCategory){
                rows.push(
                    
                );
            }
            // 商品
            rows.push(
                
            );
            // 标记最近的类别
            lastCategory = product.category;
        });
        return (
            {rows}
Name Price
); } } /** * 搜索框 */ class SearchBar extends React.Component{ constructor(props){ super(props); this.handleFilterTextChange = this.handleFilterTextChange.bind(this); this.handleInStockChange = this.handleInStockChange.bind(this); } handleFilterTextChange(e){ this.props.onFilterTextChange(e.target.value); } handleInStockChange(e){ this.props.onInStockChange(e.target.checked); } render(){ return (

{' '} only show products in stock

); } } /** * 整个页面 */ class FilterTableProductTable extends React.Component{ constructor(props){ super(props); this.state = { filterText:'', inStockOnly:false }; this.handleFilterTextChange = this.handleFilterTextChange.bind(this); this.handleInStockChange = this.handleInStockChange.bind(this); } handleFilterTextChange(filterText){ this.setState({ filterText:filterText }); } handleInStockChange(inStockOnly){ this.setState({ inStockOnly:inStockOnly }); } render(){ return (
); } } // 导出table export default FilterTableProductTable;

然后就是index.js里面渲染了。

这次探索了解了react组建拆分的原则,以及state和props的使用。

你可能感兴趣的:(react)