English 中文(简体)
是否有可能为重新接触儿童(及其推进剂)确定一种特定类型?
原标题:Is it possible to define a specific type for React Node children (and their props)?

如果我有职能部分......

const MyParent = (props:MyParentProps)=>{

 etc...
}

......在描述中,有可能确定所有儿童都必须遵守某种特定类型或界面? 页: 1

type IChild = (props:IChildProps)=> JSX.Element;

......

成功

<MyParent>
  <Child/> // That implements IChild
  <Child/>// That implements IChild
</MyParent>

失败

<MyParent>
  <BadChild/> // That doesn t implement IChild
  <Child/>// That implements IChild
</MyParent>

我只能拿打字眼来理解试图实现什么目标。

问题回答

无,是不可能的。

相反,你可以在操作时间检查<代码>ReactElement的类型。

const MyChild = () => {
  return <></>;
};

type MyParentProps = {
  children: ReactElement | ReactElement[];
};

const MyParent = (props: MyParentProps) => {
  const children = (props.children instanceof Array) ? props.children : [props.children];
  for (const child of children)
    if (child.type !== MyChild)
      throw new Error("Children of MyParent must by MyChild.");
  
  return <></>;
}

但是,由于时间过长,你可以对照某种类型或接口检查。





相关问题
How to use one react app into another react app?

I have two react apps, parent app and child app. and child app have an hash router. I have build the child app using npm run build, It creates build folder. That build folder moved into inside the ...

how to get selected value in Ant Design

I want to print the selected value, and below is my option list: const vesselName = [ { value: 0 , label: ALBIDDA , }, { value: 1 , label: ALRUMEILA , }, { value: 2 ,...

How to add a <br> tag in reactjs between two strings?

I am using react. I want to add a line break <br> between strings No results and Please try another search term. . I have tried No results.<br>Please try another search term. but ...

热门标签