如何使用带有样式组件和反应的道具更改图像源 [英] how to change image src using props with styled component and react

查看:13
本文介绍了如何使用带有样式组件和反应的道具更改图像源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为多个页面重复使用我的组件。 因此,我必须将Styled.img组件中的img src更改为传递道具。

是否可以更改样式组件上的图像源?

我应用了如下代码。 它不工作了..

//logic

import Myimg from './img/icon_my';

const OngoingLists = ({ ...props }) => {
  return (
    <ListsOutWrap>
      <ProgramListWrap {...props}>
        <IconWrap {...props} >
          <MyIcon {...props} />
        </IconWrap>
      </<ProgramListWrap>
    </ListsOutWrap>
  );
}


// styled component 
const MyIcon = styled.img.attrs({
  src: props => props.Img || { Myimg },
})`
  width: 100%;
`;

我试过了,任何图像都不显示...甚至默认的IMG文件也不显示.. 如何使用道具更改src文件?? 我应该使用背景图像吗?

提前感谢您的帮助!:)

推荐答案

样式组件仍然只是Reaction组件,在src使用时没有传递道具的情况下,您只需提供一个默认的道具值。

import Myimg from './img/icon_my';

const MyIcon = styled.img`
  width: 100%;
`;

MyIcon.defaultProps = {
  src: Myimg,
};

用法:

<MyIcon /> // uses default Myimg
<MyIcon src="/path/to/sourceImage" /> // uses "/path/to/sourceImage"

btw接受道具的正确attrs格式应该是定义一个接受道具并返回对象的函数:

const MyIcon = styled.img.attrs(props => ({
  src: props.Img || Myimg,
}))`
  width: 100px;
`;

这篇关于如何使用带有样式组件和反应的道具更改图像源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆