首页 > 解决方案 > 在 React Typescript 中为按钮组件添加图像背景

问题描述

我正在使用 React 打字稿的 React 项目中使用材质 UI 库。我希望这个按钮有一张图片作为背景。但是,该按钮不接受 src 或 imageURL 并返回打字稿错误,并且 css 样式背景也不显示图片。这是我的代码:

const noticon = require ('./../../images/nicon.png') 
const Avatarpic = require ('./../../images/Avatar.png') 

const ExampleButton = ({
  // useOpenState hook handlers
  handleToggle, handleClose, handleOpen, setOpenState, isOpen
}: DropdownButtonProps) => (
  <Button onClick={handleToggle} style={{backgroundImage: '{noticon}'}} square>
  </Button>
)
function Navbar () {
  return (
    <>
      <TopBar style={{ backgroundColor: '#e6edec' }}>
        <TopBarSection>
          <TopBarTitle>
            <Avatar imgUrl={Avatarpic} name='حسین ساداتی پور' style={{ fontFamily: 'IranSans', fontSize: '20px' }} />
          </TopBarTitle>
          <Dropdown ButtonComponent={ExampleButton}>
          <DropdownItem>Item to click</DropdownItem>
        </Dropdown>
        </TopBarSection>
        {// <TopBarSection>
          // burger menu Icon
          // </TopBarSection>
        }
      </TopBar>
      <section
        style={{
          padding: 50,
          textAlign: 'center'
        }}
      >
      Some content
      </section>
    </>
  )
}

export default Navbar

标签: cssreactjstypescriptmaterial-ui

解决方案


你需要这样做:

<Button onClick={handleToggle} style={{backgroundImage: `url(${noticon})`}} square>

推荐阅读