反应组件的动态模板

时间:2018-01-19 15:07:08

标签: reactjs

考虑以下组件: ItemsDisplay具有业务逻辑,ListTable只是具有相同界面的可视化。

class ItemsDisplay extends Component {
    componentDidMount() {
        fetch().then(items => this.setState({ items }))
    }

    remove(item) {
        // remove item from state
    }

    render() {
        return this.props.children
    }
}
const List = ({ items, onRemove }) => (
    <ul>
        {items.map(item => <li onClick="onRemove()">{item}</li>)}
    </ul>
)
const Table = ({ items, onRemove }) => (
    <table>
        {items.map(item => (
            <tr onClick="onRemove()">
                <td>{item}</td>
            </tr>
        ))}
    </table>
)

如何将ItemsDisplay与我的两种不同的可视化结合使用?那有什么模式吗?或者我需要创建一个ItemsDisplayList和另一个ItemsDisplayTable

<ItemsDisplay>
    <List items="items from ItemsDisplay" onRemove="remove rom ItemsDisplay" />
</ItemsDisplay>

<ItemsDisplay>
    <Table items="items from ItemsDisplay" onRemove="remove rom ItemsDisplay" />
</ItemsDisplay>

2 个答案:

答案 0 :(得分:1)

您可以将其设为更高阶的组件,如下所示:

const itemsDisplayFactory = (BaseComponent) => {
  return class ItemsDisplay extends Component {
    componentDidMount() {
        fetch().then(items => this.setState({ items }))
    }

    remove(item) {
        // remove item from state
    }

    render() {
      return (
        <BaseComponent
          items={this.state.items}
          onRemove={this.remove}
          // anything else that you need to pass down
          {...this.props}
        />
      )
    }
  }
}

然后你可以做

class List extends Component {
render(){
   <ul>
    {items.map(item => <li onClick={() => onRemove(item)}>{item}</li>)}
   </ul>
  }
}


class Table extends Component {
    render(){
       <table>
          {items.map(item => (
            <tr onClick={() => onRemove(item)}>
            <td>{item}</td>
            </tr>
          ))}
        </table>
      }
    }

并像这样把它组合在一起

const ItemsDisplayList = itemsDisplayFactory(List);
const ItemsDisplayTable = itemsDisplayFactory(Table);

<ItemsDisplayList />
<ItemsDisplayTable />

答案 1 :(得分:0)

const ItemDisplayList = ({ items, onRemove, list}) => {
    if(list) {
      return(
        <ul>
          {items.map(item => <li onClick="onRemove()">{item}</li>)}
        </ul>);
    } else {
    return(
        <table>
          {items.map(item => (
            <tr onClick="onRemove()">
            <td>{item}</td>
            </tr>
          ))}
        </table>);
    }
}

然后:

<ItemsDisplay>
    <ItemDsplayList list={true} items="items from ItemsDisplay" onRemove="remove rom ItemsDisplay" />
</ItemsDisplay>

<ItemsDisplay>
    <ItemDsplayList list={false} items="items from ItemsDisplay" onRemove="remove rom ItemsDisplay" />
</ItemsDisplay>