将接口属性作为参数值引用到另一个功能组件

问题描述 投票:0回答:1

如何将接口属性作为参数值引用到另一个功能组件

interface InterfaceProperties
{
   interfaceProperty1Id: number,
   interfaceProperty1Name : string
}

const tabsInterfaces: Map<InterfaceDetailEnum, JSX.Element> = new Map<InterfaceDetailEnum, JSX.Element>([
        [InterfaceDetailEnum.Detail, <InterfaceDetailMessages id={} name={} />],
        [InterfaceDetailEnum.Type, <></>],
        [InterfaceDetailEnum.Both, <></>]
    ]);

我想在下面一行中传递接口属性。

<InterfaceDetailMessages id={} name={} />]

这意味着,在

id
中,我想传递
interfaceProperty1Id
,在
name
中我想传递
interfaceProperty1Name
属性。

提前致谢

reactjs react-native react-hooks interface properties
1个回答
0
投票

您可以在映射中使用工厂方法而不是

JSX.Element
本身:

const empty = (props: InterfaceProperties) => <></>

const tabsInterfaces: Map<InterfaceDetailEnum, (props: InterfaceProperties) => JSX.Element> = new Map<InterfaceDetailEnum, (props: InterfaceProperties) => JSX.Element>([
  [InterfaceDetailEnum.Detail, props => <InterfaceDetailMessages id={props.interfaceProperty1Id} name={props.interfaceProperty1Name}/>],
  [InterfaceDetailEnum.Type, empty],
  [InterfaceDetailEnum.Both, empty]
])

这意味着您还没有创建任何组件,您将在

render()
中完成它:

export default function YourComponent() {
  const iProperties: InterfaceProperties = {interfaceProperty1Id: 1, interfaceProperty1Name: "name"} // derived from parent
  const detail: InterfaceDetailEnum = InterfaceDetailEnum.Detail // could derive from parent as well

  // map.get() has value | undefined return type
  // in case of undefined fallback to factory method which creates empty JSX.Element
  const factoryMethodToCreateTheJsxElement = tabsInterfaces.get(detail) || empty

  // now we instantiate the element
  const tab: JSX.Element = factoryMethodToCreateTheJsxElement(iProperties)
  return (
    <div>
      {tab}
    </div>
  )
}
© www.soinside.com 2019 - 2024. All rights reserved.