我有一个像这样的基于类的组件
class ArInput extends React.Component {
render() {
const { shadowless, success, error } = this.props;
const inputStyles = [
styles.input,
!shadowless && styles.shadow,
success && styles.success,
error && styles.error,
{...this.props.style}
];
return (
<Input
placeholder="write something here"
placeholderTextColor={argonTheme.COLORS.MUTED}
style={inputStyles}
color={argonTheme.COLORS.HEADER}
iconContent={
<Icon
size={14}
color={argonTheme.COLORS.ICON}
name="link"
family="AntDesign"
/>
}
{...this.props}
/>
);
}
}
我试图用react钩子将上面的类转换为基于功能的组件。这是我在typescript中想出的最好的
const ArInput =({ shadowless, success, error, style }:any)=> {
const inputStyles = [
styles.input,
!shadowless && styles.shadow,
success && styles.success,
error && styles.error,
{...style}
];
return (
<Input
placeholder="write something here"
placeholderTextColor={argonTheme.COLORS.MUTED}
style={inputStyles}
color={argonTheme.COLORS.HEADER}
iconContent={
<Icon
size={14}
color={argonTheme.COLORS.ICON}
name="link"
family="AntDesign"
/>
}
{ ...shadowless, ...success, ...error, ...style }
/>
);
}
但是这一行出现了错误{ ...shadowless, ...success, ...error, ...style }
错误是Expression expected.ts(1109)
在javascript代码中,这一行是{...this.props}
如何将javascript类转换为typescript ?
我在javascript代码中转换这行{...this.props.style}
的方式是否正确?
在道具列表中,做
{...this.props}
将从对象中提取每个单独的属性,并将其列为对象。例如,如果this.props
是{ foo: 'foo' }
,则
{...this.props}
等价于
foo="foo"
.
如果你想把这些道具放在<Input
的道具列表中,那么你可以这样做:
return (
<Input
placeholder="write something here"
placeholderTextColor={argonTheme.COLORS.MUTED}
style={inputStyles}
color={argonTheme.COLORS.HEADER}
iconContent={
<Icon
size={14}
color={argonTheme.COLORS.ICON}
name="link"
family="AntDesign"
/>
}
shadowless={shadowless}
success={success}
error={error}
style={style}
或者从道具中创建一个对象,然后将对象展开(不要展开单个道具):
return (
<Input
placeholder="write something here"
placeholderTextColor={argonTheme.COLORS.MUTED}
style={inputStyles}
color={argonTheme.COLORS.HEADER}
iconContent={
<Icon
size={14}
color={argonTheme.COLORS.ICON}
name="link"
family="AntDesign"
/>
}
{...{ shadowless, success, error, style }}
如果您打算使用TS,我还强烈建议使用比any
更精确的类型——使用any
有效地禁用了表达式的类型检查,这违背了TS的目的。
您可以尝试这样做:
interface ArInputProps{
shadowless:string; //i am assuming all of them to be of type string,you can use boolean,Function or whatever you like
success:string;
error:string;
style:string
}
const ArInput =({ shadowless, success, error, style }:ArInputProps)=> {
const inputStyles = [
styles.input,
!shadowless && styles.shadow,
success && styles.success,
error && styles.error,
{...style}
];
return (
<Input
placeholder="write something here"
placeholderTextColor={argonTheme.COLORS.MUTED}
style={inputStyles}
color={argonTheme.COLORS.HEADER}
iconContent={
<Icon
size={14}
color={argonTheme.COLORS.ICON}
name="link"
family="AntDesign"
/>
}
shadowless={shadowless}
success={success}
error={error}
style={style}
/>
);