[英]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.
我尝试在状态和 setState onClick 中创建一组禁用的项目,但我不断收到错误消息。 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)}/>
})}
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.