昨天我有以下代码,它正在使用以下代码(我正在使用 React + TypeScript)。我们来看第一段代码,父组件:
function GifExpertApp() {
const [information, setInformation] = useState<string[]>(["Ronaldo"]);
return (
<div className="App">
<header className="App-header">
<h1>Gif Expert App</h1>
<AddCategory setInformation={setInformation} />
<hr />
<ol>
{information.map((information) => {
// return <GifGrid information={information} />;
<h1>Hola</h1>;
})}
</ol>
</header>
</div>
);
}
现在让我们看看我有文本栏的组件,我在useState information
.
import React, { useState } from "react";
import { InformationProps } from "../interfaces";
function AddCategory({ setInformation }: InformationProps) {
const [inputValue, setInputValue] = useState<string>("How I met your mother");
const handleInputChange = (e: any) => {
setInputValue(e.target.value);
};
const handleSubmit = (e: any) => {
e.preventDefault(); //It avoids the page to load again when the form is submitted
if (inputValue.trim().length > 2) {
//In order to avoid insert elements without text
setInformation((information: string[]) => [...information, inputValue]);
setInputValue(" "); //Cleaning the textbar
}
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
onChange={handleInputChange}
className="textBar"
value={inputValue}
/>
</form>
);
}
export default AddCategory;
现在让我们看看界面:
// import { Dispatch, SetStateAction } from "react";
export interface InformationProps {
// setInformation: Dispatch<SetStateAction<string[]>>;
// information: string[];
setInformation: (information: string[]) => void;
}
问题是我已经开始制作另一个组件<GifGrid information={information} />
来调用所述组件中的 gifs API,我不知道 Visual Studio Code 是否被搞砸了,但它不再工作了。我的疑问如下:
我可以有这样的界面吗?因为当我尝试使用
useState
此接口中的两个 del 参数来重用我已经使用但使用新组件的同一接口时,我的问题就开始了:导出接口 InformationProps { 信息:字符串 []; setInformation: (信息: string[]) => void; }
当我将接口导入组件时,我必须使用接口的所有组件还是不是绝对必要?
该程序现在无法为我编译,因为组件的一行
AddCategory
,即:setInformation((信息: string[]) => [...信息, inputValue]);
它给了我以下错误:Argument of type '(information: string[]) => string[]' is not assignable to parameter of type 'string[]'.
我不明白为什么,因为昨天这条具有相同信息的同一行有效。有谁知道我做错了什么?谢谢问候。
当然可以,现在您有一个具有功能的界面。该setInformation函数需要一个字符串数组作为参数并且不返回任何内容。
没有必要,通过将属性声明为可选,它不再是强制性的。我在这里给你一个例子
它不会为您编译,因为该函数只需要一个字符串数组,并且您正在向它传递一个函数声明。为了让它工作,你应该像这样使用这个函数:
解决方案是在接口中的 setState 中添加使用箭头函数的可能性: