[英]How to compare two arrays in React and change className if something appears in both arrays?
I want to compare if a 'track id' appears in both the 'search results' list and the 'playlist list', and change the class name if so.我想比较“搜索结果”列表和“播放列表列表”中是否出现“曲目 ID”,如果是,则更改类名。
The following is the function I have written to do so:以下是我为此编写的函数:
onDuplicate() {
if (this.state.searchResults.filter(track => this.state.playlistTracks.includes(track.id))) {
return "Track-information-added";
} else {
return "Track-information";
}
} }
I then passed this down as a prop to the desired component and called it in the className attribute like so:然后我将它作为道具传递给所需的组件,并在 className 属性中调用它,如下所示:
alreadyAdded() {
this.props.onDuplicate();
}
render() {
return (
<div className="Track">
<div className={this.alreadyAdded}>
I then applied different CSS styles to the two class names, but nothing happens?然后我对两个类名应用了不同的 CSS 样式,但没有任何反应?
Call the function inside the className like this:像这样调用 className 中的函数:
class App extends React.Component { constructor(props) { super(props); this.state = { searchResults: [{id: 1}], playlistTracks: [1], } } onDuplicate() { const {searchResults,playlistTracks} = this.state if (searchResults.filter(track => playlistTracks.includes(track.id))) { return "Track-information-added"; } else { return "Track-information"; } } alreadyAdded() { return this.onDuplicate() } render() { return <div className={this.alreadyAdded()}>Duplicates</div>; } } React.render(<App />, document.getElementById('app'));
working link for your code: https://codepen.io/ak2403/pen/YzVKzNY您的代码的工作链接: https : //codepen.io/ak2403/pen/YzVKzNY
Happy Coding !!!快乐编码!!!
You need to call the function alreadyAdded
and return the result in this function:您需要调用函数alreadyAdded
并在此函数中返回结果:
alreadyAdded() {
return this.props.onDuplicate();
}
...
<div className = {this.alreadyAdded()}>
you forgot the return in your second function although the first one does return a value the second one does nothing with it .您忘记了第二个函数中的返回值,尽管第一个函数确实返回了一个值,而第二个函数对它没有任何作用。
alreadyAdded() {
return this.props.onDuplicate();
}
or just call the first function directly this.porps.onDuplicate()或者直接调用第一个函数 this.porps.onDuplicate()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.