簡體   English   中英

如何在反應中比較兩個數組

[英]How to compare two arrays in react

如果行的數組元素等於地圖索引,我如何返回帶有 backgroundColor 的按鈕? 這僅適用於如果 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>
    );

只需改變條件

if(lines[i] === i)

lines.includes(i)

此外,您無需再次重復相同的代碼,您可以根據條件的結果添加樣式,如下所示。

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>
  );

代替

if(lines[i] === i)

你可以做

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

這段代碼只是試圖找出我是否存在於 lineArrayItem 中。 如果不是它返回 null 這樣你就可以知道索引是否與行數組的任何項目匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM