【问题标题】:React-Bootstrap TypeScript - How to create a ImageButtonReact-Bootstrap TypeScript - 如何创建 ImageButton
【发布时间】:2021-12-02 07:02:53
【问题描述】:

我很久没有来发帖提问了,但是今天……我被困在一个新故事上,需要你的帮助!

我正在尝试使用 将设计 (html/css/jquery)(难以维护)复制到 Bootstrapreact-bootstrap.

我的原始网站上有给定的按钮:

我想用react-bootstrap 库重现它。但是,我有点卡住了,因为我不明白一两点。

我有以下组件:

image_button.tsx

import * as React from "react";
import { Button, Image } from "react-bootstrap";
import { ImageProps } from "react-bootstrap/Image";
import { ButtonProps } from "react-bootstrap/Button";

export interface ImageButtonProps {
  hoverSrc: string;
}

export interface ImageButtonState {

}

export class ImageButton extends React.Component<ImageProps & ButtonProps & ImageButtonProps, ImageButtonState> {
  render() {
    return <Button active={this.props.active} block={this.props.block} variant={this.props.variant} size={this.props.size} type={this.props.type} href={this.props.href} disabled={this.props.disabled} target={this.props.target} className={`image-button`}>
      <Image src={this.props.src}/>
    </Button>
  }
}

export default ImageButton;
  • 我想到的第一个问题是:我至少有正确的方法吗?
  • 如果我这样做了,那么将所有道具传递给我的子组件的最佳方法是什么?如您所见,我使用“映射”方法设置所有值,这可能不是最好的方法...
  • 假设我想自定义它(悬停时,更改背景图像?),如何将样式应用到我的组件?

注意:我的终极目标是拥有一个通用组件,它将所有按钮/图像道具(并应用它们)以及可以是 :hover { src: /path/to/media.png } 的 ImageButton 道具作为道具。

感谢有关该主题的任何帮助 :) 我知道这个问题很广泛,而不是专注于一个简单/精确的点 :)

最好的,

最大

【问题讨论】:

    标签: css reactjs react-bootstrap imagebutton


    【解决方案1】:

    自从添加 react hooks 以来,人们一直在转向功能组件而不是对象。

    映射所有属性的一种简单方法是使用扩展运算符,如下所示

    function ImageButton({src, ...props}) {
        return <Button {...props}>
            <Image src={src} />
        </Button>
    }
    
    export default ImageButton
    

    您也可以通过导入 css 文件 import './style.css' 来在 reactjs 旁边使用 css

    【讨论】:

    • 您好 :) 感谢您的回答!真的很有趣,我会看看它:)
    • 嘿 :) 我可以查看它,但基于上面的代码(我的),当我尝试你的方法时,将道具转发到“按钮”有效,但转发到图像时无效:/试试这个 -> &lt;Button {...this.props}&gt;&lt;Image {...this.props}/&gt;&lt;/Button&gt;。另外,考虑到这项工作,我能否像这样覆盖图像的 src(基于“悬停”之类的动作):&lt;Button {...this.props}&gt;&lt;Image {...this.props} src={this.props.hoverSrc}/&gt;&lt;/Button&gt;?谢谢:)
    • 您应该能够将道具转发到 Image。但是下一个道具将覆盖前一个。所以&lt;Image src="1" src="2" /&gt; src 只会是 2,不会是 1
    • 我明白了,这就是我的想法 :) 谢谢 :) 好吧,你自己试试吧.. 你无法将道具转发到图像,不知道为什么,我收到 webpack 错误:Uncaught (in promise) Error: Minified React error #137; visit https://reactjs.org/docs/error-decoder.html?invariant=137&amp;args[]=img for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
    • img 是一个空元素标签,既不能有children,也不能使用dangerouslySetInnerHTML。是道具之一children
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 2017-11-29
    • 2020-06-03
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    相关资源
    最近更新 更多