1)。JSX和JSX有什么区别。元素,ReactNode和ReactElement?
ReactElement和JSX。元素
是调用React的结果。直接或通过JSX编译createElement。它是一个具有类型、道具和键的对象。JSX。元素是ReactElement,其道具和类型有类型any,因此它们或多或少是相同的。
const jsx = <div>hello</div>
const ele = React.createElement("div", null, "hello");
ReactNode用作类组件中render()的返回类型。它也是PropsWithChildren属性的默认类型。
const Comp: FunctionComponent = props => <div>{props.children}</div>
// children?: React.ReactNode
它在React类型声明中看起来更复杂,但相当于:
type ReactNode = {} | null | undefined;
// super type `{}` has absorbed *all* other types, which are sub types of `{}`
// so it is a very "broad" type (I don't want to say useless...)
可以将几乎所有内容分配给ReactNode。我通常更喜欢更强的类型,但可能有一些有效的情况可以使用它。
2)。为什么类组件的呈现方法返回ReactNode,而函数组件返回ReactElement?
tl;dr:这是当前TS类型的不兼容,与核心React无关。
TS类组件:返回带有render()的ReactNode,比React/JS更宽容
TS函数组件:返回JSX。元素|为空,比React/JS更严格
原则上,React/JS类组件中的render()支持与函数组件相同的返回类型。就TS而言,由于历史原因和向后兼容性的需要,不同的类型仍然保持类型不一致。
理想情况下,一个有效的返回类型应该是这样的:
type ComponentReturnType = ReactElement | Array<ComponentReturnType> | string | number
| boolean | null // Note: undefined is invalid
3)。我怎么解这个关于null的函数?
Some options:
// Use type inference; inferred return type is `JSX.Element | null`
const MyComp1 = ({ condition }: { condition: boolean }) =>
condition ? <div>Hello</div> : null
// Use explicit function return types; Add `null`, if needed
const MyComp2 = (): JSX.Element => <div>Hello</div>;
const MyComp3 = (): React.ReactElement => <div>Hello</div>;
// Option 3 is equivalent to 2 + we don't need to use a global (JSX namespace)
// Use built-in `FunctionComponent` or `FC` type
const MyComp4: React.FC<MyProps> = () => <div>Hello</div>;
注意:避免React。FC不会把你从JSX中拯救出来。元素|空返回类型限制。
Create React App最近发布了React。FC从它的模板,因为它有一些怪癖,如隐式{children?: ReactNode}类型定义。使用React。有节制地使用FC可能更可取。
In edge cases, you can add a type assertion or Fragments as workaround:
const MyCompFragment: FunctionComponent = () => <>"Hello"</>
const MyCompCast: FunctionComponent = () => "Hello" as any
// alternative to `as any`: `as unknown as JSX.Element | null`