将材料-ui封装到自定义组件中

时间:2016-09-01 20:58:35

标签: javascript reactjs ecmascript-6 material-ui

我对await表组件有点麻烦。我将表逻辑分成了一个标题和正文组件,并在正文中,为每一行添加了一个不同的组件

material-ui

产品表组件由以下组件组成:

export const PRODUCTS = [
  {category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'},
  {category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'},
  {category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'},
  {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
  {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
  {category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}
]

export const ProductCategoryRow = ({
  product: {
    name,
    price
    }
  }) => (<TableRow>
    <TableRowColumn>
      {name}
    </TableRowColumn>
    <TableRowColumn>
      {price}
    </TableRowColumn>
  </TableRow>
)

const ProductHeader = () => (<TableHeader>
    <TableRow>
      <TableHeaderColumn>
        Name
      </TableHeaderColumn>
      <TableHeaderColumn>
        Price
      </TableHeaderColumn>
    </TableRow>
  </TableHeader>
)

export const ProductTableBody = (props) => {
  bin.log(props)
  const Products = props.products.map(product => (<ProductRow product={product} />))
  console.log(Products)
  return Products
}

我有一个webpack bin here,您可以查看一下。我已经注释掉//this does not work, the components are passed down to children and nothing happens. const ProductTable = (props) => ( <Table> <ProductHeader/> <ProductTableBody products={props.products}/> </Table> ) 不起作用。

1 个答案:

答案 0 :(得分:1)

<Table>实施依赖于其直接孩子拥有<TableHeader><TableBody>和可选的<TableFooter>组件。

如果找不到至少<TableHeader><TableBody>,那么它根本不会在其标题/正文中呈现任何内容。这就是你的情况。

解决此问题的一种方法是将<TableBody><TableHeader><Table>保持一致,但使用一些辅助函数来实现您想要的类似抽象级别。

const ProductCategoryRow = (props) => {
    const { name, price } = props.product

    return (
        <TableRow>
            <TableRowColumn>
              {name}
            </TableRowColumn>
            <TableRowColumn>
              {price}
            </TableRowColumn>
        </TableRow>
    )
}


function createHeaderColumns(columnNames) {
    return columnNames.map(name => <TableHeaderColumn>{name}</TableHeaderColumn>)
}

function createTableRows(rows) {
    return rows.map(row => <ProductCategoryRow product={row} />)
}

const ProductTable = (props) => {

    const headerColumns = createHeaderColumns(props.columnNames)
    const tableRows = createTableRows(props.products)

    return (
            <Table>
                <TableHeader>
                    <TableRow>
                        {headerColumns}
                    </TableRow>
                </TableHeader>
                <TableBody>
                    {tableRows}
                </TableBody>
            </Table>
    )
}