2017-10-12 61 views
1

我想通过一个图像的URI作为道具,所以我可以重复使用它几次反应原生。但是,这个当前的解决方案提示我需要使用字符串文字。通过本地图像URI作为道具反应原生

const ImageButton = ({ source }) => (
    <Image source={require({ source })} /> 
); 

ImageButton.propTypes = { 
    uri: PropTypes.string, 
}; 

我也试过声明URI作为PropTypes.func,做

<Image source={{ source }} /> 

但图像不会出现。什么是图像uri道具的正确实现?

回答

1

由于动态定义的字符串不可行,因此需要为需要图像执行单独的对象。

例如:

const assets = { 
    imageButton: require('./assets/button.jpg'), 
}; 

const ImageButton = (source) => { 
    <Image source={assets[source]} /> 
} 

class MyComponent extends Component(props) { 
    render() { 
    return (
     <ImageButton source={'imageButton'} /> 
    ) 
    } 
} 
+0

所以对于成为可能,都必须在同一个文件,对不对?我试图这样做,我从某处导入ImageButton,只是将它传递,但我不认为这是可能的,因为导出ImageButton没有源只会导致没有图像被呈现。 –