【问题标题】:Adding image to button using Emotion css使用 Emotion css 将图像添加到按钮
【发布时间】:2020-05-04 19:07:55
【问题描述】:

我想设置两个按钮的样式:使用情感 css 的图像向上和向下,但无法这样做。目前,我通常在函数中设置元素的样式。如何使用情感 css 实现这一目标? 我关注了https://emotion.sh/docs/introduction,但我无法以正确的方式实现它。

    import up from "../img/up.png";

    function PostButton(props) {
    let style = {
    backgroundRepeat: 'no-repeat',
    background: `url(${up})`,
    paddingRight: 24,
    paddingTop: 26,
    paddingLeft: 26,
    paddingBottom: 26.6
    };
    return (
    <button style={style} onClick={() => props.handleClick()}>{props.background}</button>
    );
    }

//I have written similar code for PostButton2


function Post(props) {
    return (
    <div>
                    <Up >
                        <PostButton src={"../images/up.png"} handleClick= . 
     {props.incrementScore} />
                    </Up>                    >

                    <Down >
                        <PostButton2 src={"../images/down.png"} 
 handleClick{props.decrementScore} />
                    </Down>
                </Col>
            </Row>
        </Container>
    </div>
    );
} 

【问题讨论】:

    标签: css reactjs typescript emotion


    【解决方案1】:

    假设 src 属性包含背景图片,我认为您需要更新背景才能使用这样的道具:

    background: `url(${props.src})`,
    

    【讨论】:

      【解决方案2】:

      使用 src 属性作为图像的路径。

      // First way, with css from emotion/react
      
      /** @jsx jsx */
      import { jsx, css } from '@emotion/react'
      
      const PostButton = ({ background, handleClick, src }) => (
        <button css={css`
          background: ${`no-repeat url(${src})`};
          padding: 26px 24px 26.6px 26px;
        `} 
        onClick={handleClick}>{background}</button>
      )
      
      // Second way, with css from emotion/css
      
      import React from 'react'
      import { css } from '@emotion/css'
      
      const PostButton = ({ background, handleClick, src }) => (
        <button className={css`
          background: ${`no-repeat url(${src})`};
          padding: 26px 24px 26.6px 26px;
        `} 
        onClick={handleClick}>{background}</button>
      )
      
      // Third way, with css from emotion/css, but pass styles as object
      
      import React from 'react'
      import { css } from '@emotion/css'
      
      const PostButton = ({ background, handleClick, src }) => (
        <button className={css({
          background: `no-repeat url(${src})`,
          padding: '26px 24px 26.6px 26px'
        })} 
        onClick={handleClick}>{background}</button>
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-24
        • 1970-01-01
        • 2014-04-06
        • 2012-09-11
        • 1970-01-01
        相关资源
        最近更新 更多