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

Encapsulating material-ui into custom components

我在使用 material-ui Table 组件时遇到了一些问题。我将 table 逻辑分为 header 和 body 组件,并在 body 内为每一行添加了不同的组件

export const PRODUCTS = [
  {category: 'Sporting Goods', price: '.99', stocked: true, name: 'Football'},
  {category: 'Sporting Goods', price: '.99', stocked: true, name: 'Baseball'},
  {category: 'Sporting Goods', price: '.99', stocked: false, name: 'Basketball'},
  {category: 'Electronics', price: '.99', stocked: true, name: 'iPod Touch'},
  {category: 'Electronics', price: '9.99', stocked: false, name: 'iPhone 5'},
  {category: 'Electronics', price: '9.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
}

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

//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 here 你可以看看。我已经注释掉了不起作用的ProductTable

<Table> 实现依赖于它的直接子组件,它有一个 <TableHeader>、一个 <TableBody> 和一个可选的 <TableFooter> 组件。

如果它至少找不到一个 <TableHeader> 和一个 <TableBody>,那么它就不会在其 header/body 中呈现任何内容。这就是您的情况。

解决此问题的一种方法是将 <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>
    )
}