【问题标题】:React-native failed propType on Image componentImage组件上的React-native失败propType
【发布时间】:2016-07-27 10:17:06
【问题描述】:

我刚刚开始使用 React-native,并且对 React 用于创建 Web 应用程序有相当不错的掌握......我在这里遇到了一个令人困惑的问题,在使用 React for Web 时从未发生过。

基本上,我正在渲染一个组件,其图像是通过映射其父组件中的对象数组来动态生成的。

export default class ImageComponent extends React.Component {
  render() {
    return (
        <Image source={this.props.source}/>
    );
  }
};

及其父组件:

export default class MainComponent extends React.Component {
  constructor(props) {
    super(props);
   this.state = {
      images:[
        { src: './src/images/1.png'},
        { src: '/src/images/2.png'},
        { src: './src/images/3.png'}
      ]
    }
   }

  render() {
    let images = this.state.images.map((image) => {
      return(<ImageComponent source={image.src}  />);
    })

    return (
      <View>
        {images}
      </View>
    );
  }
};

在设备模拟器中,我收到以下错误:

“警告:propType 失败:提供给‘Image’的无效道具‘source’检查‘BasicComponent’的渲染方法”

有人知道这里会发生什么吗?

【问题讨论】:

    标签: javascript xcode reactjs react-native


    【解决方案1】:

    您应该要求本地资产或使用带有uri 键的对象。

    所以要么在MainComponent:

    this.state = {
      images:[
        require('./src/images/1.png'),
        require('./src/images/2.png'),
        require('./src/images/3.png')
      ]
    }
    

    BasicComponent:

    return (
      <Image 
        source={{uri: this.props.source}}
      />
    );
    

    【讨论】:

    • 需要本地资产是要走的路谢谢你的帮助@zvona
    • 源道具中的 uri 属性对我有用。 require 方法没有。知道为什么吗?
    • 干杯!谢谢!顺便说一句,那不应该在文档中吗?如果您现在看到documentation,您将不得不猜测如果您没有找到这个答案......
    • 谢谢@zvona,但是你怎么知道道具是图像对象还是字符串?
    • 但在我的情况下,我有一些其他数据与图像......我将如何管理? const DATA = [ { id: 1, url: require('../../assets/country/bangladesh_one.png'), value: 'bangladesh' }, { id: 2, url: require('../ ../assets/country/india.png'), value: 'india' }, { id: 3, url: require('../../assets/country/malaysia.png'), value: 'malaysia ' }, { id: 4, url: require('../../assets/country/monaco.png'), value: 'monaco' }, ]
    【解决方案2】:

    你应该使用 uri 来设置源图像

    return (
      <Image 
        source={{uri: 'https://reactnative.dev/docs/assets/p_cat2.png'}}
      />
    );

    【讨论】:

      猜你喜欢
      • 2021-05-21
      • 1970-01-01
      • 2021-01-09
      • 2019-01-07
      • 2020-12-07
      • 1970-01-01
      • 2020-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多