I am new to React and trying to understand the basics. I have a child component called movieList that return a list of movies in a table form.
const movieList = () =>{
const {movies} = props;
return (){
<tbody>
<Fragment>
{movies.map((movie, i) => (
<tr key={i}>
<td>{movie.title}</td>
<td>{movie.genre.name}</td>
<td>{movie.numberInStock}</td>
<td>{movie.dailyRentalRate}</td>
<td><button className="btn btn-danger btn-sm" onClick={props.onClick} movie={props.movie}>Delete</button></td>
</tr>
))}
</Fragment>
</tbody>
} }
和父母
class Movies extends Component {
constructor(props) {
super(props);
this.state = { movies: getMovies(), }
}
handleDelete = (movie) => {
console.log(movie);
}
render() {
return (
<MoviesList movies={this.state.movies} onClick={() => this.handleDelete(movie)} />
);
}
}
我在桌子上正确地得到了电影列表。但是我想将按钮定位为单击按钮时删除。我知道我需要通过子组件movieList中的道具传递电影,但是我似乎无法弄清楚如何通过电影才能删除它。通过onClick属性上调用的handleDelete函数,我在控制台上得到了一个未定义的值。而我希望在单击时能获得电影的价值。我该如何在React中做到这一点。 最佳答案
很酷,所以您有电影列表,只需要删除正确的电影即可。我们将尝试通过数组中的索引删除该电影。我们将使用array.filter()
方法。请参阅沙箱以供参考:https://codesandbox.io/s/intelligent-dan-uskcy
父母
class Movies extends React.Component {
constructor(props) {
super(props);
this.state = {
movies: [
{ genre: { name: "Avengers: End Game" }, numberInStock: 100000, dailyRentalRate: 1 },
{ genre: { name: "Harry Potter" }, numberInStock: 20000, dailyRentalRate: 2 },
{ genre: { name: "DBZ" }, numberInStock: 200000, dailyRentalRate: 1}
]
}; // assuming movies is an array
}
handleDelete = movieIndex => {
const { movies } = this.state;
const updatedMovies = movies.filter((movie, index) => {
return index !== movieIndex;
});
this.setState({
movies: updatedMovies
});
};
render() {
return (
<MovieList movies={this.state.movies} handleDelete={this.handleDelete} />
);
}
}
因此handleDelete()
将索引作为参数,然后我们使用它创建一个新的电影数组,其中不包含带有传入索引的电影。
然后,在您的.map()
组件的MovieList
中,我们还将使用可用的index参数,并将该索引传递到事件处理程序props.handleDelete(i)
中。这将调用父组件中定义的handleDelete()
函数,并将更新状态。
儿童
const MovieList = (props) =>{
const {movies} = props;
return (
<tbody>
<Fragment>
{movies.map((movie, i) => (
<tr key={i}>
<td>{movie}</td>
<td>{movie.genre.name}</td>
<td>{movie.numberInStock}</td>
<td>{movie.dailyRentalRate}</td>
<td><button className="btn btn-danger btn-sm" onClick={() => props.handleDelete(i)} movie={props.movie}>Delete</button></td>
</tr>
))}
</Fragment>
</tbody>
)
}
09-25 22:11