我有一个像这样的基于类的组件
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}
/>
);
}
}
我正在尝试将上述类转换为带有反应钩子的基于功能的组件。 这是我在打字稿中想到的最好的
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}
的方式是否正确?
答案 0 :(得分:1)
在道具列表中,做
{...this.props}
将从对象中提取每个单独的属性并将其列为一个对象。例如,如果 this.props
是 { foo: 'foo' }
,则
{...this.props}
相当于
foo="foo"
在道具列表中。
您希望 props 位于 <Input
props 列表中,因此请执行以下操作:
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。
答案 1 :(得分:1)
你可以试试这样的:
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}
/>
);