gpt4 book ai didi

reactjs - 将本地镜像路径作为两个功能组件之间的 prop 传递

转载 作者:行者123 更新时间:2023-12-03 13:33:08 24 4
gpt4 key购买 nike

我正在使用react-native 开发一个项目,在该项目中我很难理解 props 在功能组件之间的工作原理。我的要求是创建一个可重用的按钮组件,我可以在其中传递项目内资源文件中的图像位置,这样它就会为我创建按钮。由于某种原因,如果我手动给出所需的位置,它将起作用并为我创建按钮,但是如果我\我将位置作为我创建的位置的 Prop 传递,则由于某种原因它将无法工作。我的代码如下。

按钮组件

import React, { Component } from 'react';
import {
View,
StyleSheet,
Image,
TouchableOpacity
} from 'react-native';

const ButtonWithImage = (props) => {
const {buttonStyle} = styles;
const clickEvent = () => {}

return (
<TouchableOpacity onPress= {clickEvent}style={buttonStyle}>
<Image
source={props.imagePath}
style={styles.ImageIconStyle}
/>
</TouchableOpacity>
);
};

const styles = {
buttonStyle: {
//alignSelf:'stretch',
height: 50,
width:50,
paddingTop:0,
flexDirection: 'row'
}
};

export default ButtonWithImage;

我创建按钮并传递 Prop 的位置

import React, { Component } from 'react';
import {
View,
StyleSheet,
Dimensions,
} from 'react-native';
import FooterIcons from './ButtonWithImage'

const Footer = () => {
return (
<View style={styles.footerStyle}>
<FooterIcons imagePath = {'./images/homeButton/homeBtn.png'} />
</View>
);
};

const styles = StyleSheet.create({
footerStyle: {
height: 60,
width: 100,
// justifyContent:'flex-start'
},
});

export default Footer;

最佳答案

这是不可能的,因为您需要具有本地路径的图像 <Image source={require(props.path)} />这不起作用,因为 require 只能将字符串文字作为参数。

这意味着您必须执行以下操作:

<FooterIcons imagePath = {require('./images/homeButton/homeBtn.png')} 
/>

为了让它发挥作用。并且不要忘记为您的图像指定宽度高度

您可以采用适合没有大量图像的应用程序的方式来完成此操作,因为我们将预加载它们:

1- 创建一个 Assets javascript 文件 asset.js ,该文件应该需要您的所有本地镜像,如下所示:

const assetsObject = {
homeIcon: require('./images/homeButton/homeBtn.png')
boatIcon: require('./images/homeButton/boat.png')
....
...
}
module.exports = assetsObject

2- 现在您需要在 ButtonWithImage.js 文件中引用此文件

const assets = require('./assets.js')

const ButtonWithImage = (props) => {
const {buttonStyle} = styles;
const clickEvent = () => {}

return (
<TouchableOpacity onPress= {clickEvent}style={buttonStyle}>
<Image
source={assets[props.imagePath]}
style={styles.ImageIconStyle}
/>
</TouchableOpacity>
);
};

3-您发送到 ButtonWithImage 的 props 应该位于我们创建的 assetObject 的键 'homeIcon' 上或'boatIcon' ..等等

const Footer = () => {
return (
<View style={styles.footerStyle}>
<FooterIcons imagePath = {'homeIcon'} />
</View>
);
};

4-不要忘记为图像指定宽度高度

就是这样,我建议不要再调用 prop imagePath,也许只是图像。

关于reactjs - 将本地镜像路径作为两个功能组件之间的 prop 传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48385073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com