输入值改变时更新列表

Update list when input value changes

我有三个组件:主组件、输入组件和列表组件。当我开始在输入字段中输入时。我希望列表更新为我输入的所有匹配结果。我有超时功能并且可以正常工作。这让我感到困惑,因为输入和列表组件不是彼此的 children 或 parents。

但是我要如何连接这些组件才能协同工作呢?

主要成分:

import React from 'react';
import ReactDOM from 'react-dom';
import Header from './Components/Header/Header'
import Input from './Components/Input/Input'
import List from './Components/List/List'
import './index.css';


ReactDOM.render(
  <React.StrictMode>
    <Header title="Contacts"/>
    <Input type="text" />
    <List />
  </React.StrictMode>,
  document.getElementById('root')
);

列表组件:

import { useState, useEffect } from 'react'
import ListItem from './ListItem'
import fetchData from '../../API/api'

import '../../index.css'

function List(params){
    const API_LINK = 'https://teacode-recruitment-challenge.s3.eu-central-1.amazonaws.com/users.json';
    const [ data , fetchedData ] = useState([]);

    const options = {
        startCallback: (data) => {return fetchedData(data)}
    }
    
    useEffect( () => {
        fetchData(API_LINK).then((data) => fetchedData(data));
    }, []) 

    return (
        <ul className="list">{data.map(
                (fetchedData) => {return <ListItem key={fetchedData.id} avatarImage={fetchedData.avatar}
                personName={fetchedData.first_name} personSurname={fetchedData.last_name} personMail={fetchedData.email}
                />}
                )}
        </ul>
    )
}

export default List;

输入组件:

import { useRef } from 'react';
import { BsSearch } from 'react-icons/bs'
import '../../index.css'

function Input(type){
    const focusInput = useRef(null)

    function makeFocus(){
        focusInput.current.focus();
    }

    function onInputChange(e){
        
        setTimeout(() => {
            console.log(e.target.value)
        }, 2500)
        
    }

    return (
        <div className="searchBar-box" onClick={makeFocus}>
            <i className="searchBar-box__icon"><BsSearch /></i>
            <input className="searchBar-box__input" ref={focusInput} type={type} onChange={onInputChange}></input>
        </div>
    )
}

export default Input;

您可以在包含输入和列表的组件中升级输入值

例如:

function ListWithFilter() {
   const [searchWord, setSearchWord] = useState('');

  return <>
    <Input value={searchWord} setValue={setSeachWord} />
    <List searchWord={searchWord} />
  </>
}

function Input (props) {
 return <input value={props.value} onChange={(e) => props.setValue(e.target.value)} />
}

function List(props) {
    const listData = ['hello', 'world', 'hello wold'];
    
    const filtered = listData.filter(s => s.includes(props.searchWord));
  
    return <div>{filtered.map(s => div)}</div>
}