【问题标题】:How to Disable button Of an Item In an array onClick React如何禁用数组中项目的按钮onClick React
【发布时间】:2020-12-31 03:45:42
【问题描述】:

我有一个单独有一个按钮的项目数组,我想在单击项目时禁用项目的按钮。我尝试在按钮的 state 和 setState onClick 中创建一组禁用的项目,但我不断收到错误消息。下面是我的组件代码。

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;

【问题讨论】:

  • 当你调用this.props.addItem 来同时在你的电影对象上设置一个禁用标志时,为什么不呢?
  • 在onClick函数中,你可以简单地写两条语句:onClick = { () =&gt; this.addingItem({...}); this.setState({ ... }) }你知道在'...'的地方要填什么

标签: javascript reactjs


【解决方案1】:

无论您在哪里映射电影,您都可以简单地检查电影是否存在于添加的电影列表中并相应地禁用该按钮。

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

【讨论】:

    猜你喜欢
    • 2022-01-11
    • 1970-01-01
    • 2020-09-01
    • 2013-02-09
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多