首页 > 解决方案 > 计算和标记相同的反应组件出现了多少次

问题描述

假设我有这些孙子组件:

孙子一号.tsx

import React from "react";

const GrandchildOne = () => {
  const label = ? // get the index

  return <>One: {label}</>
}

export default GrandchildOne;

孙子二号.tsx

import React from "react";

const GrandchildTwo = () => {
  const label = ? // get the index

  return <>Two: {label}</>
}

export default GrandchildTwo;

然后是一个子组件:

import React from "react";

type Props = {
  selector: boolean[];
}

const Child = (props: Props) => {
  // something

  return
    <>
      Child component: <br />
      props.selector[0] ? <GrandchildOne /> : null
      <br />
      props.selector[1] ? <GrandchildTwo /> : null
      <br />
    </>
}

export default Child;

和父组件:

应用程序.tsx

import React from "react";

const App = () => {
  // something

  return
    <>
      <Child selector={[false,true]}/> // shows 1
      foobar <br />
      <Child selector={[true,true]/> // shows 2
    </>
}

export default App;

我希望它呈现为:

Child component:

Two: 1
foobar
Child component:
One: 1
Two: 2

如何让孙子组件显示指示父组件中组件索引的标签?
我无法手动将道具传递给孙子组件或子组件。

我想useRef可能是关键,但不知道如何实现它。

标签: javascriptreactjstypescript

解决方案


推荐阅读