Javascript Image 组件上的 React-native 失败 propType

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36460827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:06:31  来源:igfitidea点击:

React-native failed propType on Image component

javascriptxcodereactjsreact-native

提问by Maxwelll

I am just starting out with React-native and have a pretty decent grasp on React for creating web apps... I am running into a confusing issue here that never occured when working with react for the web.

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

Basically I am rendering a component whose image is being dynamically generated by mapping over an array of objects in its parent component.

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

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

And its parent component:

及其父组件:

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>
    );
  }
};

In device simulator I am getting the following error:

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

"Warning: Failed propType:Invalid prop 'source' supplied to 'Image' check the render method of 'BasicComponent'"

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

Does anyone know what could be going on here?

有谁知道这里会发生什么?

回答by Samuli Hakoniemi

You should either require the local assets or use object with urikey.

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

So either in MainComponent:

所以无论是在MainComponent

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

or in BasicComponent:

或在BasicComponent

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

回答by Nguy?n Quang Tu?n

you should be use uri for set source image

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

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