【问题标题】:React Native using list of image in state with for loopReact Native 使用带有 for 循环的状态图像列表
【发布时间】:2020-09-25 15:08:21
【问题描述】:

我是 React Native 的初学者。我想使用图像列表,然后使用 for 循环将它们推送到子页面

这是我的代码来解释我在说什么。

    state ={
    a: ['./assest/image1.jpg','./assest/image2.jpg','./assest/image3.jpg'],
  }

  b = () => {
    let d = [];
    for (var i = 0; i<=this.state.a.lenght - 1; i++){
    if (this.state.a[i] == ' ') { }
    else {
    d.push(<Child images={this.state.a[i]} />)
      }
    }
    return d;
    };
 
    render() {
    return <ScrollView style={styles.body}>

      {this.b()}
    </ScrollView>
    }
    }
    

这是子页面的代码,它给出了图像 url 并使用 props 设置它

    constructor(props)
{
super(props);
}

  render()
  {
  
  return <View style ={ styles.body}>


<Image style={styles.image}>{this.props.images}</Image>
  </View>
    }
  }

在状态中使用图片网址列表的正确方法是什么

以及如何使用 for 循环推送它们

【问题讨论】:

    标签: image react-native for-loop state


    【解决方案1】:
    state = {
        a: ['./assest/image1.jpg','./assest/image2.jpg','./assest/image3.jpg'],
      }
    
    render() {
        return (
           <ScrollView style={styles.body}>
           {
              this.state.a.map((url,key) => 
                 <View style ={ styles.body}>
                     <Image 
                        style={styles.image} 
                        source={require(url)} // <--- changed
                      />
                 </View>
              )
           }
           </ScrollView>
        )
    }
    

    【讨论】:

    • 我应该在 {key} 中写什么?
    • 没什么。只需复制粘贴代码即可。只要你有时间,我真的建议你阅读 js 的“map”和“forEach”函数,因为它们将成为你开发的基础。
    • 谢谢,大括号和圆括号写对了吗,/>后面有错误
    • 我在 '/>' 之后添加了 ')'。现在应该没事了。
    • 我遇到了两个错误,第一个错误: 组件不能包含子组件。如果您想在图像顶部呈现内容,请考虑使用 组件或绝对定位。在我将 Image 更改为 Imagebackground 然后遇到另一个错误:必须在 组件中呈现文本字符串。
    猜你喜欢
    • 1970-01-01
    • 2019-11-28
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 2020-11-04
    • 1970-01-01
    • 2017-02-18
    相关资源
    最近更新 更多