【问题标题】:How to pass a function as a parameter in React?如何在 React 中将函数作为参数传递?
【发布时间】:2022-11-20 19:32:04
【问题描述】:

我正在尝试将一个函数从父组件传递到子组件,以使子组件更改父组件的状态。基本上我有一个搜索栏需要更改主页上显示的内容。

当我检查父函数的类型时,它显示为一个函数,但是当我在子函数中发送并检查它时,它的类型是未定义的。每当我尝试在子组件中调用它时,我都会收到一个错误,它不是一个函数

import LineChart from "./charts/LineChart";
import React, { Component } from 'react';
import Player from "../Components/Player";
import SearchBar from '../Components/SearchBar';

class Future extends Component {
    state = {
        players: [],
        data: [],
        playerID : ""
    };


    async componentDidMount() {
        if (Player.playerID == "") {
            const response = await fetch('http://localhost:8080/random');
            const body = await response.json();
            this.setState({ players: body });
            console.log(body[0].player_id);
            this.setState({ playerID: body[0].player_id })
            this.setData(body[0].player_id)
        } else {
            this.displayPlayer(Player.playerID)
            this.setData(Player.playerID)
        }
    }

    async displayPlayer(playerID) {
        if (playerID != "") {
            const response = await fetch('http://localhost:8080/get_player/' + playerID);
            const body = await response.json();
            this.setState({ players: body });
        }
    }

    onSearchChange = (value) => {
        this.setState({ playerID: value });
    }

    async setData(id) {
        const response = await fetch('http://localhost:8080/goal_prediction/' + id);
        const body = await response.json();
        this.setState({ data: body });
        console.log(body);
}

    render() {
        this.displayPlayer(Player.playerID)
        const { players, data, id } = this.state;
        return (
            <div>
                <SearchBar placeholder={"Search"} stateChange={this.onSearchChange} />
                {players.map(player =>
                    <div key={player.id}>
                        {player.name}'s goals
                    </div>
                )}
                <LineChart />
                Goals predicted for next season: {data.predicted_goals }
            </div>
        );
    }
}
export default Future;
import './SearchBar.css';
import React, { useState } from 'react';
import CloseIcon from '@mui/icons-material/Close';
import SearchIcon from '@mui/icons-material/Search'; 
import Player from '../Components/Player';
import Future from '../pages/FutureStats';


function SearchBar({ placeholder }, { stateChange }) {

const [filteredData, setFilteredData] = useState([]);
const [wordEntered, setWordEntered] = useState("");

const handleFilter = async (event) => {
    const searchWord = event.target.value                                   // Access the value inside input
    setWordEntered(searchWord);
    const url = 'http://localhost:8080/search_player/' + searchWord;
    const response = await fetch(url);
    const body = await response.json();
    if (searchWord === "") {
        setFilteredData([])
    } else {
        setFilteredData(body);
    }
}

const clearInput = () => {
    setFilteredData([]);
    setWordEntered("");
    }

    const selectInput = value => () => {
        console.log(Player.playerID)
        Player.playerID
        setFilteredData([]);
        setWordEntered("");
        console.log(typeof(stateChange))
        stateChange(value);
    }

  return (
    <div className='search'>
          <div className='searchInputs'>
              <input type={"text"} value={wordEntered} placeholder={placeholder} onChange={handleFilter} />
            <div className='searchIcon'>
                {filteredData.length === 0 ? <SearchIcon/> : <CloseIcon id="clearButton" onClick={clearInput} />}  
            </div>
        </div>

        {filteredData.length !== 0 && (
            <div className='dataResult'>
            {filteredData.slice(0, 15).map((value) => {
                return (
                    // Stay on one page.
                    <a className="dataItem" target="_blank" rel="noopener noreferrer" onClick={selectInput(value.player_id)}>
                        <p key={value.id}>{value.name}</p>
                 </a>
                 );
            })}
        </div>
        )}
    </div>
  );
}

export default SearchBar;

【问题讨论】:

  • 你正试图从错误的对象中提取它——从上下文中。第一个对象是道具,你已经在提取占位符从它开始,第二个是上下文,你确实没有任何东西,所以你应该有类似 { placeholder, stateChange } 的东西
  • 只有一个道具可以解构SearchBar({ placeholder, stateChange })

标签: javascript reactjs


【解决方案1】:

stateChange 是你的道具的一部分,需要成为你的 SearchBar 函数中的第一个参数:

function SearchBar({ placeholder, stateChange }) {
...

【讨论】:

    猜你喜欢
    • 2017-10-25
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    相关资源
    最近更新 更多