本文介绍了比较两个数组,如果id相等则禁用单个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在状态中有两个数组,并且都有ID.

I have two array in the state and both have id's.

如果某个数组具有相同的值(在这种情况下为8),我想禁用所有具有该相等值的按钮.

if some array have the same value (In this case 8) I would like to disable all the buttons that have this equal value.

按钮已经存在,我只想禁用具有相同非唯一ID的按钮.

The buttons already exist, I just want to disable the ones that have the same non-unique ids.

我尝试过这样,但是我没有得到

I tried like this but i'm not getting it

var setOne = [2,6,8];
var setTwo = [3, 8, 4]

const button = () => {
var hasDuplicateValues = [...new Set(setOne)].filter(item => setTwo.includes(item));

if(hasDuplicateValues.length > 0) {
   <button disabled />
}
else {
    <button />
}
}

render(){
this.button()
}

此解决方案禁用了所有按钮,但我只想禁用具有相同ID的按钮.

This solution is disabling all the buttons but i want to disable the one with the same id only.

谢谢

推荐答案

目前尚不清楚该组件在应用程序层次结构中的哪个位置,因此我尝试了一些猜测工作.事物的外观几乎就在那里.您只需要遍历按钮并创建它们.

It's not quite clear where in the app hierarchy that component is so I've attempted a bit of guess work. You're almost there by the looks of things. You just need to iterate over the buttons and create them.

function Button(props) {
  const { disabled, text } = props;
  return <button disabled={disabled}>{text}</button>;
}

// Buttons creates the buttons in the set
function Buttons() {

  const setOne = [2, 6, 8];
  const setTwo = [3, 8, 4];

  // Remove the duplicates from the combined sets
  const combined = [...new Set([...setOne, ...setTwo])];

  // Get your duplicate values
  const hasDuplicateValues = setOne.filter(item => setTwo.includes(item));

  // `map` over the combined buttons
  // If `hasDuplicateValues` includes the current button, disable it
  return combined.map((n) => (
    <Button
      text={n}
      disabled={hasDuplicateValues.includes(n) && 'disabled'}
    />
  ));

}

ReactDOM.render(<Buttons />, document.querySelector("#root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"/>

这篇关于比较两个数组,如果id相等则禁用单个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 10:59