我正在为 TextInput 创建一个自定义组件。但是当我尝试将函数 prop 传递给自定义组件时遇到了问题。这是代码
// Screen.tsx
export const RegisterScreen = ({props}: Props) => {
const [text, setText] = useState("");
const onChangeInputText = (text: string) => setText(text);
return (
<View>
<CustomInput onChangeText={onChangeInputText} text={text} />
</View>
// CustomTextInput.tsx
type Props = {
onChangeText: () => void;
text?: string;
};
export const CustomInput = ({ onChangeText, text }: Props) => {
return (
<TextInput
style={styles.container}
onChangeText={onChangeText}
value={text}
placeholder="Type here"
/>
);
};
使用此代码,我收到此错误
Type '(text: string) => void' is not assignable to type '() => void'
我想我知道是什么原因造成的(可能是在类型声明上?)但由于这实际上是我第一次尝试 TypeScript,我真的不知道如何解决这个问题。首先尝试谷歌搜索,但我没有发现任何与我类似的错误。
答案 0 :(得分:2)
这个函数的类型定义说“嘿,我需要传递一个字符串才能完成我的工作”:
it('should scroll', fakeAsync(() => {
component.highlightsContainer.nativeElement.scrollIntoView = jest.fn();
component.scrollToHighlightsContainer();
tick();
expect(component.highlightsContainer.nativeElement.scrollIntoView)
.toHaveBeenCalled();
}));
但是 onChangeText 属性的定义是“我不会向你传递任何东西”:
library("ggpubr")
library("grid")
library("gridExtra")
# Density plot of "Sepal.Length"
#::::::::::::::::::::::::::::::::::::::
density.p <- ggdensity(iris, x = "Sepal.Length",
fill = "Species", palette = "jco")
# Draw the summary table of Sepal.Length
#::::::::::::::::::::::::::::::::::::::
# Compute descriptive statistics by groups
stable <- desc_statby(iris, measure.var = "Sepal.Length",
grps = "Species")
stable <- stable[, c("Species", "length", "mean", "sd")]
# Summary table plot, medium orange theme
stable.p <- ggtexttable(stable, rows = NULL,
theme = ttheme("mOrange"))
p <- arrangeGrob(density.p, stable.p,
ncol = 1,
heights = c(2, 1))
grid.draw(p)
你的代码实际上会传递一个字符串,所以你应该只需要更新 prop 上的类型。
const onChangeInputText = (text: string) => setText(text);