【问题标题】:Passing image URL to functional component in React native将图像 URL 传递给 React Native 中的功能组件
【发布时间】:2022-02-02 14:12:48
【问题描述】:

我希望我的头像组件显示带有传递给组件的 URL 的头像。因此,如果我通过 avatar1,它会显示 avatar1。我尝试了几种方法,但似乎没有任何效果。

我的头像组件目前看起来像这样。我想摆脱静态网址

export default function Avatar() {

  return (
    <Image source={require("../assets/avatar.png")} style={styles.avatarStyle} />
  );
}
const styles = StyleSheet.create({
  avatarStyle: {
    resizeMode: 'contain',
    height: "60%",
    alignSelf: "flex-start",
    position: "absolute",
    bottom: 0
  }
});

【问题讨论】:

    标签: javascript reactjs react-native parameter-passing react-functional-component


    【解决方案1】:

    可能你试图通过 props 传递这个 avatar1,所以你需要使用 props,将它传递给函数

    export default function Avatar({avatarUri}) {
        
          return (
            <Image source={{uri: avatarUri}} style={styles.avatarStyle} />
          );
        }
        const styles = StyleSheet.create({
          avatarStyle: {
            resizeMode: 'contain',
            height: "60%",
            alignSelf: "flex-start",
            position: "absolute",
            bottom: 0
          }
        });
    

    https://reactnative.dev/docs/props

    【讨论】:

    • 你叫它:?
    • 没错,但如果您的头像只是本地图像的路径,您必须将 source={{uri: avatarUri}} 更改为 source={require(avatarUri)}
    • 它没有用。 “第 6 行的调用无效:require(avatarUri)”
    【解决方案2】:

    确保接下来的事情:

    • Image path检查路径是否正确
    • 你应该将width样式参数添加到图像中,这是必需的 进行渲染。
    • resizeMode 这是 Image 的道具,而不是样式参数

    固定样式:

    const styles = StyleSheet.create({
      avatarStyle: {
        height: "60%",
        width: 150, // FOR EXAMPLE
        alignSelf: "flex-start",
        position: "absolute",
        bottom: 0
      }
    });
    

    完整代码:

    export default function Avatar() {
    
      return (
        <Image source={require("../assets/avatar.png")} style={styles.avatarStyle} resizeMode='contain'/>
      );
    }
    const styles = StyleSheet.create({
      avatarStyle: {
        height: "60%",
        width: 150, // FOR EXAMPLE
        alignSelf: "flex-start",
        position: "absolute",
        bottom: 0
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2020-09-07
      • 1970-01-01
      • 2021-04-29
      • 2019-01-18
      • 2017-02-19
      • 2020-09-04
      • 2019-02-18
      • 1970-01-01
      • 2019-12-06
      相关资源
      最近更新 更多