代码之家  ›  专栏  ›  技术社区  ›  Alwaysblue

在React Native中设计星形图案

  •  5
  • Alwaysblue  · 技术社区  · 7 年前

    我试着在本地的react中绘制星体图案,那里应该是方形的,而不是星星。

    星形图案像这样

    ****
    ****
    ****
    ****
    ****
    

    在Vanila JS中,它看起来像

    let rows=5;
     for(let i=1; i <= 5; i++) {
      for(let j=1; j<=5; j++){   
       document.write('*');
      }
      document.write('<br />');
    }
    

    但这就是vanila JS,我希望在react本机功能组件中实现相同的功能,然后在JSX中显示它。

    在react native中考虑这个我的功能组件

    let numberOfBoxesRequired = 4; 
    let array = []
    
    const gridBoxes  = (props) => {
    
        for (let i=0; i<numberOfBoxesRequired; i++) {
            for (let j=0; j<numberOfBoxesRequired; j++) {
    
            }
        }
        return (
            <View style={mainGridBox}>  
    
            </View>
        )
    }
    

    问题:我该怎么做?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Estus Flask    7 年前

    在普通的javascript和react中是相同的:

    const starLines = Array(4).fill('*'.repeat(4));
    

    一旦有了数据,就可以以特定于当前应用程序的方式输出。

    在纯JavaScript中:

    document.write(starLines.join('<br />'));
    

    在react native中:

    <View style={mainGridBox}>{starLines.map(line => <Text>{line}</Text>)}</View>
    
        2
  •  1
  •   Stundji    7 年前

    首先,您需要渲染您的框:

    let numberOfBoxesRequired = 4; 
    
    const gridBoxes  = (props) => {
        let boxes = [];
        for (let i=0; i<numberOfBoxesRequired; i++) {    
            for (let j=0; j<numberOfBoxesRequired; j++) {
                boxes.push(<Box />); // assume Box is your box component
            }
    
        }
        return (
            <View style={mainGridBox}>  
                {boxes} // render the boxes
            </View>
        )
    }
    

    然后,您将不得不设置网格框的样式:

    .mainGridBox {
      flex: 1,
      flexWrap: "wrap";
    }
    
    .box {
      flexBasis: 0.25; // this will make a box fill 25% of the container width
      width: 30;  // example width
      height: 30; // example height
    }
    

    这是最接近您的实现,但我建议您使用 Array.map() 喜欢 埃斯图斯 在他的回答中指出。

    推荐文章