4

我有一个反应组件,它表示带有文本和一些脚注的文档。文本应呈现如下:

This the first footnote[1], this is the second[2].

Here is another [3].

当我渲染我的组件时,我想在每次看到脚注时进行计数,以便它增加。树可以有很多层次,所以你不能假设所有的脚注都是主要组件的直接子级。

这也应该是动态的,以便添加引用更新计数。

我想不出一种非常“反应灵敏”的方式来做到这一点。上下文(尽管不受欢迎)似乎不是正确的事情,否则,您将没有有关相邻组件的信息。

4

1 回答 1

3

我想我会这样处理它...

在您的容器或顶级组件中,创建一个用于保存脚注的数组。然后将此数组作为道具传递给可能呈现脚注的任何组件,以及必须在任何其他组件之后呈现的脚注呈现组件。

const DocComponent = () => {
  const footnotes = [];
  return (
    <div>
       <SomeContent footnotes={footnotes} />
       <SomeOtherContent footnotes={footnotes} />
       <EvenDifferentContent footnotes={footnotes} />
       <Footnotes footnotes={footnotes} />
    </div>
  );
};

请注意,脚注数组必须通过 props 向下传递到所有可以呈现对脚注的引用的组件。每次组件呈现脚注引用时,它都会向数组添加脚注,如下所示:

const SomeContent = ({footnotes}) => {
  footnotes.push('This is the footnote text.');
  const footnoteIndex = footnotes.length;
  return (<p>Hermansen and Shihipar, et al [{footnoteIndex}]</p>);
};

当执行到达脚注组件时,相同的脚注数组实例将通过 prop 传递给它。在执行时,数组将填充所有需要显示的脚注。您可以直接以简单的方式渲染它们:

const Footnotes = ({footnotes}) => {
  const inner = footnotes.map( 
    (footnote, index) => (<li>[{index+1}] {footnote}</li>) );
  return (<ul>{inner}</ul>);
}; 

这种实现肯定与组件的渲染顺序耦合。因此,渲染中的组件顺序应该与您希望脚注出现的视觉顺序相匹配。

这是一个 jsfiddle - https://jsfiddle.net/69z2wepo/79222/

于 2017-05-22T16:52:31.447 回答