简体   繁体   中英

Importing React Autosuggest as Functional Component from Another JSX File

I'm currently making a simple web frontend with react using react-autosuggest to search a specified user from a list. I want to try and use the Autosuggest to give suggestion when the user's type in the query in the search field; the suggestion will be based on username of github profiles taken from github user API.

What I want to do is to separate the AutoSuggest.jsx and then import it into Main.jsx then render the Main.jsx in App.js, however it keeps giving me 'TypeError: _ref2 is undefined' and always refer to my onChange function of AutoSuggest.jsx as the problem.

Below is my App.js code:

import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import Header from './views/header/Header';
import Main from './views/main/Main';
import Footer from './views/footer/Footer';

const App = () => {
  return (
    <>
      <Header/>
      <Main/> <- the autosuggest is imported in here
      <Footer/>
    </>
  );
}

export default App;

Below is my Main.jsx code:

import React, { useState } from 'react';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import axios from 'axios';
import { useEffect } from 'react';
import AutoSuggest from '../../components/AutoSuggest';

const Main = () => {
    const [userList, setUserList] = useState([]);

    useEffect(() => {
        axios.get('https://api.github.com/users?per_page=100')
        .then((res) => setUserList(res.data))
        .catch((err) => console.log(err));
    }, [])

    return (
        <Container>
            <br/>
            <Row>
                <AutoSuggest userList={userList} placeHolderText={'wow'} />
            </Row>
        </Container>
    );
}

export default Main;

Below is my AutoSuggest.jsx code:

import React, { useState } from "react";
import Autosuggest from 'react-autosuggest';

function escapeRegexCharacters(str) {
    return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function getSuggestions(value, userList) {
    const escapedValue = escapeRegexCharacters(value.trim());

    if (escapedValue === '') {
        return [];
    }

    const regex = new RegExp('^' + escapedValue, 'i');

    return userList.filter(user => regex.test(user.login));
    }

    function getSuggestionValue(suggestion) {
    return suggestion.name;
}

function renderSuggestion(suggestion) {
    return (
        <span>{suggestion.name}</span>
    );
}

const AutoSuggest = ({userList, placeHolderText}) => {
    const [value, setValue] = useState('');
    const [suggestions, setSuggestions] = useState([]);

    const onChange = (event, { newValue, method }) => { <- error from console always refer here, I'm not quite sure how to handle it..
        setValue(newValue);
    };

    const onSuggestionsFetchRequested = ({ value }) => {
        setValue(getSuggestions(value, userList))
    };

    const onSuggestionsClearRequested = () => {
        setSuggestions([]);
    };

    const inputProps = {
        placeholder: placeHolderText,
        value,
        onChange: () => onChange()
    };

    return (
        <Autosuggest 
        suggestions={suggestions}
        onSuggestionsFetchRequested={() => onSuggestionsFetchRequested()}
        onSuggestionsClearRequested={() => onSuggestionsClearRequested()}
        getSuggestionValue={() => getSuggestionValue()}
        renderSuggestion={() => renderSuggestion()}
        inputProps={inputProps} />
    );
}

export default AutoSuggest;

The error on browser (Firefox) console:

类型错误 _ref2 未定义

I have no idea what does the error mean or how it happened and therefore unable to do any workaround.. I also want to ask if what I do here is already considered a good practice or not and maybe some inputs on what I can improve as well to make my code cleaner and web faster. Any input is highly appreciated, thank you in advance!

you have to write it like this... do not use the arrow function in inputProps

        onChange: onChange

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM