简体   繁体   中英

How to Disable button Of an Item In an array onClick React

I have an array of items which individually has a button, I want to disable the button of an item when I click on the Item. I have tried creating an array of disabled items in the state and setState onClick of the Button but I keep getting errors. Here is my Component code below.

class MovieSummary extends Component {
  constructor(props) {
    super(props);

    this.state = {
   
      disabled: [],
    };
  }

  addingItem = (item) => {
    this.props.addItem(item);
  };

  render() {
    const { Title, imdbID } = this.props.movie;
    return (
      <div>
        {" "}
        <h5>
          {this.props.movie.Title}{" "}
          <button
            key={imdbID}
            disabled={this.state.disabled.indexOf(imdbID) !== -1}
            onClick={
              (() =>
                this.addingItem({
                  title: Title,
                  id: imdbID,
                }),
              this.setState({
                disabled: [...this.state.disabled, imdbID],
              }))
            }
          >
            Nominate
          </button>
        </h5>
      </div>
    );
  }
}

export default MovieSummary;

Wherever you're mapping through movies, you could simply check whether the movie exists in the added movies list or not and disable the button accordingly.

class ComponentThatWrapsMovieSummary extends Component {
  state = {
    addedMovies: [],
  }
  
  render() {
    return (
      {movies.map(movie => {
        // wherever you're mapping, you could simply check like this.
        return <MovieSummary isDisabled={this.addedMovies.includes(movie.id)}/>
      })}
    )
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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