Reactjs 如何将返回类型设置为React.StatelessComponent?
这是有效的:Reactjs 如何将返回类型设置为React.StatelessComponent?,reactjs,typescript,Reactjs,Typescript,这是有效的: import * as React from 'react'; export default (props: any): JSX.Element => { return ( <h1>{props.children}</h1> ) } import*as React from'React'; 导出默认值(props:any):JSX.Element=>{ 返回( {props.children} ) } 这是一个错误: import
import * as React from 'react';
export default (props: any): JSX.Element => {
return (
<h1>{props.children}</h1>
)
}
import*as React from'React';
导出默认值(props:any):JSX.Element=>{
返回(
{props.children}
)
}
这是一个错误:
import * as React from 'react';
export default (props: any): React.StatelessComponent => {
return (
<h1>{props.children}</h1>
)
}
import*as React from'React';
导出默认值(props:any):React.StatelessComponent=>{
返回(
{props.children}
)
}
如何将返回类型设置为
React.StatelessComponent
?实际上,您需要拆分组件及其导出:
const MyComp: SFC<{}> = (props: any) => {
return (
<h1>{props.children}</h1>
)
}
export default MyComp
constmycomp:SFC=(道具:任意)=>{
返回(
{props.children}
)
}
导出默认mycop
要在同一语句中声明和强制转换,您可能必须使用将组件的类型设置为
有关实际示例,请参见下文
// Types.
type Props = any
// Export.
export default (props =>
<h1>{props.children}</h1>
) as React.StatelessComponent<Props>
//类型。
类型Props=any
//出口。
导出默认值(道具=>
{props.children}
)作为React.stateless组件
不要使用默认导出,它是一种反模式
import * as React from 'react';
export const MyComponent: React.StatelessComponent = (props) => <h1>{props.children}</h1>
import*as React from'React';
导出常量MyComponent:React.StatelessComponent=(props)=>{props.children}
请注意,我还删除了
return
关键字和花括号,因为它是一个箭头函数,除了返回JSX之外,它不做任何事情,您在使用什么?流动?Typescript?用Typescript标记更新几乎写下了我的答案假设流:)不幸的是,我认为不使用as
,就不可能导出并在同一语句中分配类型。是的,我意识到了这一点,并在你发表评论之前编辑了我的答案。将整个组件包装在paren中并使用as
操作符是一个巧妙的技巧。虽然,从可读性角度来看,我不知道这对于稍大一点的SFC会是什么样子。谢谢。在避免时,它往往更有意义。我发现它在合并时最有用,因为在逻辑上,部分可能与整个@Mrchief具有相似/相同的名称