简体   繁体   English

如何在反应中比较两个数组

[英]How to compare two arrays in react

how can i return buttons with backgroundColor if lines's array's element equals to map index ?如果行的数组元素等于地图索引,我如何返回带有 backgroundColor 的按钮? this only works for if lines = [0,1,2] ,这仅适用于如果 lines = [0,1,2] ,

let lines=[0,6,9]
 return (
        <div>
            {new Array(9).fill(null).map((e, i) => {
                let color='green';
                if(lines[i] === i) {
                return (
                        <React.Fragment key={i}>
                        <button style={{backgroundColor:this.props.color}}>MyButton {i}<button/>
                        {(i+1) % props.width === 0 && <br />}
                       </React.Fragment>
                      )
                }

                return(

                    <React.Fragment key={i}>
                        <button>MyButton {i}<button/>
                        {(i+1) % props.width === 0 && <br />}
                    </React.Fragment>
                )
            })}
        </div>
    );

Just change the condition from只需改变条件

if(lines[i] === i)

to

lines.includes(i)

Also you need not repeat the same code again instead, you can add the styles based on the condition's result like below.此外,您无需再次重复相同的代码,您可以根据条件的结果添加样式,如下所示。

let lines=[0,6,9]
   return (
    <div>
      {new Array(9).fill(null).map((e, i) => {
        let color = "green";
        let styles = {};
        if (lines.includes(i)) {
          styles = { backgroundColor: this.props.color };
        }
        return (
          <React.Fragment key={i}>
            <button type="button" styles={styles}>
              MyButton {i}
            </button>
            {(i + 1) % props.width === 0 && <br />}
          </React.Fragment>
        );
      })}
    </div>
  );

instead of代替

if(lines[i] === i)

you can just do你可以做

if (lines.find(lineArrayItem => lineArrayItem === i))

this code just try to find out if i is present in lineArrayItem .这段代码只是试图找出我是否存在于 lineArrayItem 中。 if Not it returns null so that way you can know if the index matches with any item of lines array or not.如果不是它返回 null 这样你就可以知道索引是否与行数组的任何项目匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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