材质UI:菜单重构

时间:2017-03-01 20:56:38

标签: reactjs material-ui

正在尝试重构我的菜单,该菜单使用材料用户界面中的列表。

无意义的菜单如下所示

    <SelectableList id="menu" value={location}>
    <ListItem primaryText="Encoding" primaryTogglesNestedList={true} value="/encoding" nestedItems={[
        <ListItem primaryText="Base32" containerElement={<Link to="/base32"/>} value="/base32"/>,
        <ListItem primaryText="Base32Hex" containerElement={<Link to="/base32Hex"/>} value="/base32Hex"/>,
        <ListItem primaryText="Base64" containerElement={<Link to="/base64"/>} value="/base64"/>,

并且显然有很多样板,所以我决定创建一个自定义组件,它将处理代码中的重复项

import React from 'react';
import {ListItem} from 'material-ui/List'
import {Link} from 'react-router'

const MenuItem = ({anchor, ...other}) => (
    <ListItem containerElement={<Link to={anchor} />} value={anchor} {...other} key={"item-"+ anchor}/>
);


export default MenuItem;

问题是,当我使用它时

<MenuItem primaryText="Base32" anchor="/base32" />

menuItem不再可选。此外,要从 SelectableList id =“menu”value = {location} 中调用值(为了扩展菜单,当重新加载页面时),我还必须为MenuItem添加值标记(背叛的。)

我应该如何处理这种重构?

更新 JSFiddle(简化示例):https://jsfiddle.net/1vk8wzoc/27/

1 个答案:

答案 0 :(得分:1)

好的,所以看看你的JSFiddle和Material UI来源,看起来他们拒绝没有某些属性的孩子:

https://github.com/callemall/material-ui/blob/master/src/List/makeSelectable.js#L18

extendChild(child, styles, selectedItemStyle) {
  if (child && child.type && child.type.muiName === 'ListItem') {
    ....

因此,您的组件永远不会收到样式以指示其已选中。

我会在这里做两件事之一:

  1. 可能会与图书馆一起举办PR以支持HOC 列表项目
  2. 或者,使用复制所有内容的React.cloneElement 所需的东西,所以它似乎是正确的元素 makeSelectable功能