我正在将项目从js转换为Typescript,然后在一个组件中将props传递给material-ui主题以根据输入进行更改。
react功能组件的相关部分如下:
import React from 'react';
import {makeStyles} from "@material-ui/core/styles";
// @ts-ignore
import {SketchPicker} from 'react-color';
import InputAdornment from "@material-ui/core/InputAdornment";
const useStyles = makeStyles(theme => ({
colorSwatch: props => ({
width: theme.spacing(5),
height: 30,
border: '1px solid black',
borderRadius: theme.spacing(0.25),
backgroundColor: props.embedColor,
}),
}));
export default function FormFragmentEmbed(props: any) {
const { register, errors } = props.form;
const { defaultValues } = props;
const [colorPicker, setColorPicker] = React.useState<string>(defaultValues.embedColor);
const classes = useStyles({
embedColor: watchColor,
});
return (
<TextField
name={'embedColor'}
label={'Embed Color'}
defaultValue={colorPicker}
error={errors.embedColor !== undefined}
inputRef={register({})}
InputProps={{
endAdornment: <InputAdornment position="end"><Box className={classes.colorSwatch}/></InputAdornment>
}}
/>
}
但是我在backgroundColor
中定义makeStyles
的行给我一个错误
TS2339:类型“ {}”上不存在属性“ embedColor”。
如何解决该错误?
也是半相关的,如您所见,我添加了一条衬线以忽略SketchPicker
的导入,因为TS试图导入时出现了错误。导入该错误的正确方法是什么?
答案 0 :(得分:0)
尝试使用此语法,
const useStyles = makeStyles({
colorSwatch: props => ({
width: theme.spacing(5),
height: 30,
border: '1px solid black',
borderRadius: theme.spacing(0.25),
backgroundColor: props.embedColor,
}),
});
export default function FormFragmentEmbed(props: any) {
const { register, errors } = props.form;
const { defaultValues } = props;
const [colorPicker, setColorPicker] = React.useState<string>(defaultValues.embedColor);
const classes = useStyles(defaultValues);
return (
<TextField
name={'embedColor'}
label={'Embed Color'}
defaultValue={colorPicker}
error={errors.embedColor !== undefined}
inputRef={register({})}
InputProps={{
endAdornment: <InputAdornment position="end"><Box className={classes.colorSwatch}/></InputAdornment>
}}
/>
}
现在我猜您的代码应该可以正常工作了。 Official documentation链接可将道具与makeStyles和useStyles一起使用。