将material-ui封装到定制组件中

Encapsulating material-ui into custom components

本文关键字:组件 material-ui 封装      更新时间:2023-09-26

我在material-ui表组件上遇到了一点麻烦。我将表逻辑分离为header和body组件,并在body中为每一行添加了不同的组件

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
}

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

//this does not work, the components are passed down to children and nothing happens.
  const ProductTable = (props) => (
    <Table>
      <ProductHeader/>
      <ProductTableBody products={props.products}/>
    </Table>
  )

我这里有一个webpack bin,你可以看看。我已经注释掉了不工作的ProductTable

<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>
    )
}
相关文章: