为什么函数没有作为道具传递给另一个组件的 onClick

why is function not being passed as props to onClick of another component

我是 React JS 的新手,遇到了一个问题。我正在尝试传递 openPopup,它 returns 错误是 openPopup 不是函数。我已经在 MovieCard.JS 中完成了诸如解构 openPopup 之类的所有操作,但无济于事。我想传递点击卡片的 imbdID。有人可以帮忙吗? 谢谢你。 `

class Status extends Component {
    state = {
        isLoading: true,
        movies: null,
        search: '',
    }

    openPopup = id => {
        console.log(id)
    }

    render() {
        const { isLoading, movies } = this.state;
        console.log(this.state);
    return (
        <div className='homapage'>
        <h1>Find your favourite movies on IMDB</h1>
        <div className='movies-result-cards'>
        {!isLoading ? (
            movies.map(movie=> <MovieCard key={movie.imdbID} {...movie} openPopup={this.openPopup} />)
        ): (movies === null && isLoading ? <h3> </h3> : <h3>...Loading </h3>)}
        </div>
        </div>
    )}

}
`

import React from 'react';
import './MovieCard.css'

const MovieCard = (props, openPopup) => {
    const { Title, Poster, Type, Year, imdbID} = props;
    return (
    <div className='card'>
        <button onClick={() => openPopup(imdbID)}>View Order</button>
            <h1>{Title.length > 20 ? Title.substring(0, 20) + '...' :
             Title}</h1>
            <img src={Poster} alt={Title}/>
            <p>{Type}</p>
            <p>{Year}</p>
    </div>
    )
}

export default MovieCard;

    TypeError: openPopup is not a function
onClick
F:/practice/classified website/classified-site/src/Components/MovieCard.js:8
   5 | const { Title, Poster, Type, Year, imdbID} = props;
   6 | return (
   7 | <div className='card'>
>  8 |     <button onClick={() => openPopup(imdbID)}>View Order</button>
     | ^   9 |         <h1>{Title.length > 20 ? Title.substring(0, 20) + '...' :
  10 |          Title}</h1>
  11 |         <img src={Poster} alt={Title}/>

您需要使用props.openPopup()

import React from 'react';
import './MovieCard.css'

const MovieCard = (props) => {
    const { Title, Poster, Type, Year, imdbID} = props;
    return (
    <div className='card'>
        <button onClick={() => props.openPopup(imdbID)}>View Order</button>
            <h1>{Title.length > 20 ? Title.substring(0, 20) + '...' :
             Title}</h1>
            <img src={Poster} alt={Title}/>
            <p>{Type}</p>
            <p>{Year}</p>
    </div>
    )
}

导出默认 MovieCard;

如果你试图使用解构方式,那么你所做的就是错误的。试试这个:

import React from 'react';
import './MovieCard.css'

const MovieCard = ({openPopup,...rest}) => {
    const { Title, Poster, Type, Year, imdbID} = rest;
    return (
    <div className='card'>
        <button onClick={() => openPopup(imdbID)}>View Order</button>
            <h1>{Title.length > 20 ? Title.substring(0, 20) + '...' :
             Title}</h1>
            <img src={Poster} alt={Title}/>
            <p>{Type}</p>
            <p>{Year}</p>
    </div>
    )
}

export default MovieCard;