javascript - 或者通过使用状态来 react native 渲染组件

标签 javascript reactjs react-native react-native-ios

我想将列表交替呈现为网格中的两列。我打算在组件状态中使用标志变量来实现此目的,并在每次返回 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>
    );
  }
}

最佳答案

我认为在这种情况下您不需要更改状态。只需将参数传递给您的 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>
  );
}

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

关于javascript - 或者通过使用状态来 react native 渲染组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46835291/

相关文章:

javascript - JSON 对象 -> 数组?我应该如何转换它?

javascript - 将样式应用于文本框子字符串

reactjs - 使用 M :N relationship with sequelize on postgres 创建实体

javascript - Reactjs 为 render 方法定义变量的最佳策略

javascript - 使用 Set 的不同值

javascript - 带有 React-Native 和 mapStateToProps 的 Redux

javascript - 取消绑定(bind) jQuery 事件处理程序

javascript - 复制标题属性值并插入为 InnerHTML

reactjs - 如何在我的 App.js View 中导入和使用此文件

javascript - 在 react native 中从 sqlite 存储返回查询结果时未定义