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

时间:2020-07-05 13:00:00

标签: reactjs react-props react-component

我是React JS的新手,但遇到了问题。我正在尝试通过openPopup,它返回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}/>

1 个答案:

答案 0 :(得分:1)

您需要使用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;