使用带有React的TypeScript,我们不再需要扩展React.Props,以便编译器知道所有的反应组件道具都可以有子代:
interface MyProps { }
class MyComponent extends React.Component<MyProps, {}> {
public render(): JSX.Element {
return <div>{this.props.children}</div>;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,无状态功能组件似乎不是这样的:
const MyStatelessComponent = (props: MyProps) => {
return (
<div>{props.children}</div>
);
};
Run Code Online (Sandbox Code Playgroud)
发出编译错误:
错误:(102,17)TS2339:"MyProps"类型中不存在属性"children".
我想这是因为编译器真的没办法知道children在props参数中会给出一个vanilla函数.
所以问题是我们应该如何在TypeScript中使用无状态功能组件中的子项?
我可以回到以前的方式MyProps extends React.Props,但Props界面被标记为已弃用,无状态组件没有或支持Props.ref我理解它.
所以我可以children手动定义道具:
interface MyProps {
children?: React.ReactNode;
}
Run Code Online (Sandbox Code Playgroud)
第一:是ReactNode正确的类型?
第二:我必须将子项写为optional(?),否则消费者会认为它children应该是component()的属性,<MyStatelessComponent children={} />如果没有提供值,则会引发错误.
好像我错过了一些东西.任何人都可以清楚地说明我的最后一个例子是否是在React中使用无子功能组件和子项的方法?
我已经创建了一个基于Material-UI 的 Button 组件的自定义按钮组件,所以我可以在一个动作挂起时覆盖一个加载圆圈。但是,React 抱怨以下内容:
警告:收到false非布尔属性loading。如果要将其写入 DOM,请改为传递字符串:loading="false" 或 loading={value.toString()}。
这是我的组件的样子。提前致谢!
import * as React from 'react'
import { ButtonProps } from '@material-ui/core/Button'
import { Button, CircularProgress } from '@material-ui/core'
interface IProps extends ButtonProps {
loading: boolean
}
export const LoadingButton = (props: IProps) => {
const { disabled, loading } = props
return (
<div className='button-container'>
<Button {...props} disabled={disabled == true || loading == true}/>
{loading == true && (
<CircularProgress size={24} className='button-progress' /> …Run Code Online (Sandbox Code Playgroud)