【问题标题】:Implement an Autocomplete Component in React-Typescript在 React-Typescript 中实现自动完成组件
【发布时间】:2021-06-01 03:16:02
【问题描述】:

我是 React-Typescript 的新手。我想使用反应打字稿在我的项目中创建自动完成文本框。我在谷歌搜索我得到了一些示例代码。我尝试在我的应用程序中使用。我遇到了一些错误。

在我的 Autocomplete.tsx 中,我遇到了一些错误,我将在下面解释我的错误,当我在 index.tsx 中绑定自动完成组件时,我在数据中遇到了错误。

AutoComplete.tsx

import react, { ChangeEvent, FC, useState } from "react";
import styled from "styled-components";
import { FaArrowDown } from "@react-icons/all-files/fa/FaArrowDown";

import {
    AutoCompleteContainer,
    AutoCompleteIcon,
    Input,
    AutoCompleteItem,
    AutoCompleteItemButton
} from "./styles";
const Root = styled.div`
    position: relative;
    width: 320px;
`;

interface IData {
    name: string;
    code: string;
}
interface autoCompleteProps {
    iconColor?: string;
    inputStyle?: react.CSSProperties;
    optionsStyle?: react.CSSProperties;

    data: any[];
}
export const AutoComplete: FC<autoCompleteProps> = ({
    iconColor,
    inputStyle,
    optionsStyle,
    data
}) => {
    const [search, setSearch] = useState({
    text: "",
    suggestions: []
    });
    const [isComponentVisible, setIsComponentVisible] = useState(true);
    const onTextChanged = (e: ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    let suggestions = [];
    if (value.length > 0) {
        const regex = new RegExp(`^${value}`, "i");
        suggestions = data.sort().filter((v: IData) => regex.test(v.name));
    }
    setIsComponentVisible(true);
    setSearch({ suggestions, text: value });
    };

    const suggestionSelected = (value: IData) => {
    setIsComponentVisible(false);

    setSearch({
        text: value.name,
        suggestions: []
    });
    };

    const { suggestions } = search;

    return (
    <Root>
        <div
        onClick={() => setIsComponentVisible(false)}
        style={{
            display: isComponentVisible ? "block" : "none",
            width: "200vw",
            height: "200vh",
            backgroundColor: "transparent",
            position: "fixed",
            zIndex: 0,
            top: 0,
            left: 0
        }}
        />
        <div>
        <Input
            id="input"
            autoComplete="off"
            value={search.text}
            onChange={onTextChanged}
            type={"text"}
            style={inputStyle}
        />
        <AutoCompleteIcon color={iconColor} isOpen={isComponentVisible}>
            <FaArrowDown />
        </AutoCompleteIcon>
        </div>
        {suggestions.length > 0 && isComponentVisible && (
        <AutoCompleteContainer style={optionsStyle}>
            {suggestions.map((item: IData) => (
            <AutoCompleteItem key={item.code}>
                <AutoCompleteItemButton
                key={item.code}
                onClick={() => suggestionSelected(item)}
                >
                {item.name}
                </AutoCompleteItemButton>
            </AutoCompleteItem>
            ))}
        </AutoCompleteContainer>
        )}
    </Root>
    );
};

索引.tsx

import { render } from "react-dom";
import { AutoComplete } from "./AutoComplete";
import data from "./data.json";

const rootElement = document.getElementById("root");
render(
    <>
    <h2>Simple-React Autocomplete Functional-component Tsx</h2>

    <AutoComplete
        inputStyle={{ backgroundColor: "PaleTurquoise" }}
        optionsStyle={{ backgroundColor: "LemonChiffon" }}
        data={data}
        iconColor="Turquoise"
    />
    </>,
    rootElement
);

数据.json

[
    { "name": "Afghanistan", "code": "AF" },
    { "name": "Åland Islands", "code": "AX" },
    { "name": "Albania", "code": "AL" },
    { "name": "Algeria", "code": "DZ" },
    { "name": "American Samoa", "code": "AS" },
    { "name": "AndorrA", "code": "AD" },
    { "name": "Angola", "code": "AO" },
    { "name": "Anguilla", "code": "AI" }
]

在 index.ts 文件中,当我绑定 data={data} 值时出现错误 (JSX 属性) autoCompleteProps.data: any[]

Type '{}' is missing the following properties from type 'any[]': length, pop, push, concat, and 28 more.ts(2740)
AutoComplete.tsx(27, 3): The expected type comes from property 'data' which is declared here on type 'IntrinsicAttributes & autoCompleteProps & { children?: ReactNode; }'

Autocomplete.tsx 文件(如何解决问题)

在建议行错误:(属性)建议:从不[]

Type 'any[]' is not assignable to type 'never[]'.
    Type 'any' is not assignable to type 'never'.ts(2322

【问题讨论】:

    标签: reactjs react-redux react-hooks react-typescript


    【解决方案1】:

    我建议您尝试更改此设置

    interface autoCompleteProps {
        iconColor?: string;
        inputStyle?: react.CSSProperties;
        optionsStyle?: react.CSSProperties;
    
        data: IData[];
    }
    

    还有这个

    const [search, setSearch] = useState({
        text: "",
        suggestions: [] as IData[]
        });
    

    还有这个

    let suggestions : IData[] = [];
    

    【讨论】:

      猜你喜欢
      • 2020-12-12
      • 2022-01-12
      • 2015-10-26
      • 2017-07-10
      • 2013-01-28
      • 1970-01-01
      • 2016-06-23
      • 2018-10-31
      • 2018-04-23
      相关资源
      最近更新 更多