【问题标题】:Button with image using React Typescript使用 React Typescript 的带有图像的按钮
【发布时间】:2020-05-03 17:56:57
【问题描述】:

我正在使用 React Typescript。

  1. 如何将图像添加到我的按钮?
    我试过这样做,没有错误,但我得到一个空白按钮。
  2. 如何在此处使用 Emotion CSS 设置按钮元素的样式?
import React from "react";

function PostButton(props){
    let style = {
        width:24,
        height:24,
        src: "../images/abc.png"
    };
    return(
        <button style={style} onClick={() => props.handleClick()}>{props.label}</button>
    );
}

return (
    <div style={style}>
        <PostButton src={"../images/abc.png"} handleClick = {props.incrementScore}/>
    </div>
);
}

【问题讨论】:

    标签: css reactjs typescript emotion


    【解决方案1】:

    Damian 的回答在技术上是正确的,但是如果您使用 webpack,则需要像这样导入图像:

    import abc from "../images/abc.png";
    

    并像这样使用它:

    function PostButton(props){
        let style = {
            width:24,
            height:24,
            background: `url(${abc})`,
        };
        return(
            <button style={style} onClick={() => props.handleClick()}>{props.label}</button>
        );
    }
    

    【讨论】:

      【解决方案2】:

      src 将是 background:url(../images/abc.png) 也许您对img HTML 元素所具有的src 属性感到困惑?

      也许您应该在按钮中包含一个嵌套的img 组件。

      工作示例:https://stackblitz.com/edit/react-emotion-hello-u9qyaa

      【讨论】:

        猜你喜欢
        • 2020-07-30
        • 1970-01-01
        • 1970-01-01
        • 2014-09-20
        • 1970-01-01
        • 2016-09-01
        • 2011-02-11
        • 2017-09-21
        • 1970-01-01
        相关资源
        最近更新 更多