javascript - 计算和标记相同的反应组件出现了多少次
问题描述
假设我有这些孙子组件:
孙子一号.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
可能是关键,但不知道如何实现它。
解决方案
推荐阅读
- sql - SUM 函数 SQL Server
- sql-server - Set Variable for Select Result in SQL Server
- windows - 在 BAT 文件中,按修改时间比较文件:“if file1 is-older-than file2 do”?
- python-3.x - 我的简单损失函数导致 NAN
- python - 将本地文件引用到 Python 文件
- vue.js - 无论Vuetify卡片中是否隐藏内容,如何修复按钮?
- android - 导入 android.app.NotificationChannel 错误
- jquery - 验证 Bootstrap 4 时复选框下方的错误消息
- jms - jms queue receiver which always run in backgrond
- javascript - 将 callack 的值绑定到实例 nodejs 的属性