我绝对不是React的新手,需要创建一个按钮来将用户从当前组件(MovieView
)带到主要组件(MainView)
。我设法正确创建了它,并使用onClick
触发了我知道我不能从一个函数调用类(如控制台所说),所以我创建了另一个要调用并触发MainView
的函数,但是您可能会想,它不起作用。这是我正在使用的代码:
MainView
您能看到这为您指出要采取的道路,还是我如何正确地称呼此import React from 'react';
import { MainView } from '../main-view/main-view';
function NewButton() {
return <MainView />;
}
export class MovieView extends React.Component {
constructor() {
super();
this.state = {};
}
render() {
const { movie } = this.props;
if (!movie) return null;
return (
<div className="movie-view">
<img className="movie-poster" src={movie.imagePath} />
<div className="movie-title">
<span className="label">Title: </span>
<span className="value">{movie.title}</span>
</div>
<div className="movie-description">
<span className="label">Description: </span>
<span className="value">{movie.plot}</span>
</div>
<div className="movie-genre">
<span className="label">Genre: </span>
<span className="value">{movie.genre.name}</span>
</div>
<div className="movie-director">
<span className="label">Director: </span>
<span className="value">{movie.director.name}</span>
</div>
<div className="back-movies">
<button onClick={NewButton}>Back</button>
</div>
</div>
);
}
}
类。我知道这是一个简单的任务,但是我恐怕还没有吸收React原理。预先感谢大家。
设置跟踪在MainView
事件中应渲染MainView
的状态变量。 (布尔值可能就足够了)
onClick
中:render()
的内容。MovieView
组件。MainView
),则可能只需将URL更新为链接到react-router
组件的URL。MainView
import React from "react";
import { MainView } from '../main-view/main-view';
export const MovieView = ({ movie }) => {
const { showMainView, setShowMainView } = React.useState(false);
if (!!movie) {
return null;
}
function toggleMainView() {
setShowMainView(true);
}
return (
<React.Fragment>
{ showMainView ? (
<MainView />
) : (
<div className="movie-view">
<img className="movie-poster" src={movie.imagePath} />
<div className="movie-title">
<span className="label">Title: </span>
<span className="value">{movie.title}</span>
</div>
<div className="movie-description">
<span className="label">Description: </span>
<span className="value">{movie.plot}</span>
</div>
<div className="movie-genre">
<span className="label">Genre: </span>
<span className="value">{movie.genre.name}</span>
</div>
<div className="movie-director">
<span className="label">Director: </span>
<span className="value">{movie.director.name}</span>
</div>
<div className="back-movies">
<button onClick={() => toggleMainView()}>Back</button>
</div>
</div>
)}
</React.Fragment>
);
};
export default MovieView;
return
它已更改为:
return (
<div className="main-view">
{selectedMovie
? <MovieView movie={selectedMovie} />
: movies.map(movie => (
<MovieCard key={movie._id} movie={movie} onClick={movie => this.onMovieClick(movie)} />
))
}
</div>
谢谢大家。