我正在尝试创建一个现在接受 2 组输入 + 标签的组件。
import React from 'react'
import MyLogic from './MyLogic';
interface MyProps {
url1: string
text1: string
url2: string
text2: string
}
const MyLogic: React.FC<MyProps> = props => {
const { url1, text1, url2, text2 } = props;
return (
<>
<MyLogic {...{ url: url1, text: text1 }} />
<MyLogic {...{ url: url2, text: text2 }} />
</>
)
}
export default MyLogic;
明白了吗?
我需要动态处理 props,因为有时可能有 100 个输入,每个输入都需要一个索引,其中第一个输入需要 { url: url1, text: text1 }
,100 个需要 { url: url100, text: text100 }
。
因此,如果发生这种情况,我将不得不调用 MyLogic
组件 100 次。
<MyLogic {...{ url: url1, text: text1 }} />
<MyLogic {...{ url: url2, text: text2 }} />
...
<MyLogic {...{ url: url97, text: text97 }} />
<MyLogic {...{ url: url98, text: text98 }} />
... // and so on
重要
我没有解释一个重要的部分。
我需要这个的原因是因为我正在使用一个外部服务,它通过名称读取道具;
read: [{ name: 'text1', url: 'url1' }, { name: 'text2', url: 'url2', ... }]
这就是它读取 prop 值的方式。可能会执行以下操作:{ name: 'input.text1' }
等。不知道您是否明白我的意思。
那么我怎样才能以最动态的方式处理这个问题?
答案 0 :(得分:4)
使用一个对象数组,每个对象是单个输入的属性。现在您可以映射输入数组,并传播属性。
interface InputProps {
url: string
text: string
}
interface MyProps {
inputs: InputProps[]
}
const MyLogic: React.FC<MyProps> = ({ inputs }: MyProps) => (
<>
{inputs.map(p => (
<MyLogic {...p} />
))}
</>
);