简体   繁体   English

将清单孩子传递给父母

[英]Passing List Children to the Parent

    
  
 
  
  
  
    
       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>
        } }
    
    
And the Parent

 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)} /> ); } } 

I get the list of movies correctly on the table. 我在桌子上正确地得到了电影列表。 But I want to target the button for delete on button click. 但是我想将按钮定位为单击按钮时删除。 I understand that I need to pass the movie as props from the child component movieList but I cant seem to figure out how to pass the movie for me to be able to delete. 我知道我需要通过子组件movieList中的道具传递电影,但是我似乎无法弄清楚如何通过电影才能删除它。 With the handleDelete function called on the onClick property, I get an undefined value on the console. 通过onClick属性上调用的handleDelete函数,我在控制台上得到了一个未定义的值。 Whereas I expect to get the value of a movie when I click. 而我希望在单击时能获得电影的价值。 How can I do this in React. 我该如何在React中做到这一点。

Cool so you have a list of movies and you just need to remove the right movie. 很酷,所以您有电影列表,只需要删除正确的电影即可。 We're going to try removing the movie it by its index in our array. 我们将尝试通过数组中的索引删除该电影。 We'll use the array.filter() method. 我们将使用array.filter()方法。 See sandbox for reference: https://codesandbox.io/s/intelligent-dan-uskcy 请参阅沙箱以供参考: https : //codesandbox.io/s/intelligent-dan-uskcy

Parent

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} />
    );
  }
}

So handleDelete() takes an index as an argument, and we use that to create a new array of movies, that do not include the movie with the index you passed in. 因此handleDelete()将索引作为参数,然后我们使用它来创建新的电影数组,其中不包含带有传入索引的电影。

Then in the .map() of your MovieList component, we'll use the available index parameter as well, and pass that index inside the event-handler, props.handleDelete(i) . 然后,在MovieList组件的.map()中,我们props.handleDelete(i)使用可用的index参数,并将该索引传递到事件处理程序props.handleDelete(i) That will call the handleDelete() function defined in the parent component and it will update state. 这将调用父组件中定义的handleDelete()函数,并将更新状态。

Child 儿童

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>
  )
}

You need to pass the movie element through your callback. 您需要通过回调传递movie元素。 Change your child-components onlick to: 将您的子组件onlick更改为:

onClick={() => props.onClick(movie)}

Afterwards you need to pass the data from the callback to your function in your parent 之后,您需要将数据从回调传递给父级中的函数

onClick={movie => this.handleDelete(movie)}

or just 要不就

onClick={this.handleDelete}

Then all you need to do is remove the movie from the list in your state. 然后,您所要做的就是从您所在州的列表中删除电影。 React will then remove the element from the DOM: 然后,React将从DOM中删除该元素:

handleDelete = (movie) => {
   const { movies } = this.state;
   const newMoviews = movies.slice();
   newMovies.splice(newMovies.findIndex(m => m.title === movie.title), 1)
   this.setState({ movies: newMovies });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM