如何打破这些 React 展示组件之间的紧密耦合

How to break the tight coupling between these React Presentational Components

一些 tutorials/examples 的 React 应用程序以似乎具有紧密耦合组件的方式显示数据。例如:

class List extends React.Component {
    render() {
        <div className="table-responsive">
            <table className="table table-hover">
                <thead>
                    <tr>
                      <th>A</th>
                      <th>B</th>
                      <th>C</th>
                      <th>D</th>
                    </tr>
                </thead>
                <tbody>
                    {items.map(item => <ListItem key={item.id} ... />)}
                </tbody>
            </table>
        </div>
    }

你可以想象ListItem是什么样子的。没有 List 就无法使用 ListItem,因为它们必须共享相同的布局。

我看不出这对创建可重用组件有何帮助。有办法解决吗?

我认为耦合实际上并没有那么紧密。您只需要进行一项更改即可在渲染循环中使用另一个组件,并且 <ListItem /><List />.

一无所知

我看不到任何长期利益,但您可以通过允许它接受上下文标签作为道具或作为高阶组件的参数来使 <ListItem /> 更通用。

function ListItem({ Row='tr', Cell='td', key, item }) {
  return (
    <Row key={key}>
      <Cell>{item}</Cell>
    </Row>
  );
}

这将允许您通过向下传递不同的标签在非 table 上下文中使用它。

<ListItem key={1} item="foo" Row="div" Cell="span" />

这将呈现为更通用 HTML。

<div>
  <span>foo</span>
</div>

您可以对 <List /> 做同样的事情,让它也接受 <ListItem /> 组件作为道具。

但我认为这比它们的价值更麻烦,而且你最终会浪费更多的时间来编写和测试这些通用解耦,而不是如果你只是解决你的例子中相当松散的耦合。