【问题标题】:React: Image source INVALID prop (source uses string with adress to the image)React:图像源无效道具(源使用带有图像地址的字符串)
【发布时间】:2020-04-26 16:23:44
【问题描述】:

在图像块中,源使用来自 PlayerInfo 的字符串数组。 PlayerInfo 包含数组字符串:

require('../img/player1.jpg')
require('../img/player2.jpg')

在下图中,我使用了

(image source= {item.item}) 

--> 让它看起来像这样

(image source = require('../img/player1.jpg'))

但这似乎不起作用。我必须在源内部进行哪些更改才能显示图像?

enter image description here

【问题讨论】:

标签: reactjs react-native


【解决方案1】:

为了使用<Image>,你应该给它一个静态资源。所以问题就在这里:

[...playerInfo, `require('../img/player${numPlayer}.jpg')`]

您可以使用如下代码实现相同的功能:

const playerInfo=[
  {
    "index" : "1",
    "item" : require('../img/player1.jpg'),
  },
  {
    "index" : "2",
    "item" : require('../img/player2.jpg'),
  }
]

但我认为,如果您有大量玩家,创建自定义图像组件会更方便:

class CustomizedImage extends Component {
    constructor(props) {
       super(props); 
    } 

    render() { 
       return (
         <Image source= {this.props.source} 
                resizeMode="contain" 
                style={{ height: this.props.height, width: this.props.width}} /> 
       ); 
    } 
}

然后像这样使用它:

<CustomizedImage source= {require(`../img/player${numPlayer}.jpg`)} 
                 height={100}
                 width={100}             
/> 

我还没有运行它,但它应该可以正常工作。创建您自己的自定义组件也是开发应用程序的好方法,因为您可以随时更改您的包(例如使用“react-native-fast-image”)或其他配置。

【讨论】:

    猜你喜欢
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多