React Native Rendering Components 或者通过使用状态

React Native Rendering Components Alternatively by using state

我想将列表交替呈现为网格中的两列。我打算在我的组件状态中使用一个标志变量并在每次 return a CardDetail.

时更改它的值

我注释掉了 this.changeState() 语句,因为它们似乎没有按预期工作。

请帮我弄清楚,我是 React/React Native 的新手。 提前致谢。

renderAlbums() {
    return this.state.albums.map(album =>{
      this.rend2(album)
    }
    );
  }
rend2(album){
if(this.state.flag === 0)
{
  //this.changeState();
  return (<CardDetail key={album.title} album={album}  />);
}
else
{
 //this.changeState;
return (<View />);
} 
}

changeState(){
  if(this.state.flag === 0)
{
this.setState({flag:1});
}
else
{
  this.setState({flag:0})
}
}

  render() {
    console.log(this.state);

    return (

      <ScrollView>
      <Grid>
      <Col>{this.renderAlbums()}</Col>
        <Col>{this.renderAlbums()}</Col>

      </Grid>
      </ScrollView>
    );
  }
}

也许稍微改变一下您的方法,同时呈现两列。因此,您可以在要呈现的列之间切换 CardDetail.

return (
  <ScrollView>
    <Grid>
      {this.state.albums.map((album, index) => 
        <View key={index}>
          <Col>{index % 2 === 0
            ? <CardDetail key={album.title} album={album}  />
            : <View />
          }</Col>

          <Col>{index % 2 !== 0
            ? <CardDetail key={album.title} album={album}  />
            : <View />
          }</Col>
        </View>
      }
    </Grid>
  </ScrollView>

我认为在这种情况下您不需要更改状态。只需将一个参数传递给您的 renderAlbums() 方法,然后使用它来挑选列表中的所有其他专辑:

renderAlbums(col) {
  return this.state.albums.map( (album, index) => {
    if (index % 2 == col)
      return (<CardDetail key={album.title} album={album}  />);
    else
      return (<View/>);
  } );
}

然后在您的 render() 方法中:

render() {
  return (
    <ScrollView>
      <Grid>
        <Col>{this.renderAlbums(0)}</Col>
        <Col>{this.renderAlbums(1)}</Col>
      </Grid>
    </ScrollView>
  );
}

此代码尚未经过测试,但应该可以。