集合组件

列表和其他类型的集合某种程度上也可以用组件来描述.

为了避免完全给列表新建一个单独的组件, 我们可以使用以下这种写法.

const SearchSuggestions = (props) => {
  // renderSearchSuggestion() behaves as a pseudo SearchSuggestion component
  // keep it self contained and it should be easy to extract later if needed
  const renderSearchSuggestion = listItem => (
    <li key={listItem.id}>{listItem.name} {listItem.id}</li>
  );

  return (
    <ul>
      {props.listItems.map(renderSearchSuggestion)}
    </ul>
  );
};

如果你想在更复杂的场景里面或者其他什么地方使用这个组件, 你能很轻松的复制这段代码到新的组件中. (不要过度设计组件) If things get more complex or you want to use this component elsewhere, you should be able to copy/paste the code out into a new component. Don’t prematurely componentize.

参考资料:

results matching ""

    No results matching ""