Javascript 设置复杂的反应内联样式,例如悬停,在按钮等反应组件上处于活动状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38699039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:43:58  来源:igfitidea点击:

Setting Complex react inline styles such as hover, active on react components such as button

javascriptcssreactjssass

提问by WitVault

I have the following styles in css for my buttons. I am also using bootstrap.

我的按钮在 css 中有以下样式。我也在使用引导程序。

.btn-primary {
    background-color: #229ac8;
    background-image: linear-gradient(to bottom, #23a1d1, #1f90bb);
    background-repeat: repeat-x;
    border-color: #1f90bb #1f90bb #145e7a;
    color: #ffffff;
    text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
}
.btn-primary:hover, .btn-primary:active, .btn-primary.active, .btn-primary.disabled, .btn-primary[disabled] {
    background-color: #1f90bb;
    background-position: 0 -15px;
}

I have defined a button as a component in react.

我在 react 中定义了一个按钮作为组件。

const MyButton = ({children, onClick, classNames, ...rest }) =>
(
    <button
        onClick   = {onClick}
        className = {`${classNames}`}
        {...rest}
    >
        {children}
    </button>
);

Based on some value fetched from the server I want to change the complete color of the button.

基于从服务器获取的一些值,我想更改按钮的完整颜色。

Question 1:

问题 1:

How can I set the button's complete style as inline style?

如何将按钮的完整样式设置为内联样式?

Question 2:

问题2:

Also, can I use some scssfeatures like mixinsin reactto generate button styles dynamically passing coloras variable ?

另外,我可以使用一些scssmixinsin 之类的功能react来生成动态传递颜色作为变量的按钮样式吗?

Question 3:

问题 3:

Should I use inline styles or classnames using css in js?

我应该在 js 中使用 css 使用内联样式还是类名?

For a generic component such as a button should we use a global class which can be reused in all places where button is defined or use a local inline style and create inline styles in all places?

对于像按钮这样的通用组件,我们应该使用一个可以在所有定义按钮的地方重用的全局类,还是使用本地内联样式并在所有地方创建内联样式?

采纳答案by ahmedelgabri

CSS in JS (with pseudo classes & MQ support)

JS 中的 CSS (具有伪类和 MQ 支持)

There are lots of libs to write CSS with Reactthat supports pseudo classes but all, if not all of them requires you to inline or write your CSS in JS Which I highly recommend

很多库可以使用支持伪类的React 编写 CSS,但如果不是所有这些库都需要您在 JS 中内联或编写 CSS,我强烈推荐

CSS Modules (Write your CSS as normal, but in a better way)

CSS 模块(像往常一样编写 CSS,但以更好的方式编写)

There is also CSS moduleswhich if you are already using Webpack should be simple to set it up, which let you import/requireyour CSS as an object use it your component like so:

还有一些CSS 模块,如果你已经在使用Webpack 应该很容易设置它,它让你import/require你的 CSS 作为一个对象使用你的组件,像这样:

import styles from './Button.css'

const MyButton = ({children, onClick, type='primary', ...rest }) =>
(
    <button
        onClick   = {onClick}
        className = {styles.primary}
        {...rest}
    >
        {children}
    </button>
);

Decoupling your components

解耦你的组件

I'd also add that you shouldn't pass classes to the <Button />and deal with the conditions inside the component itself. For example using classnameslibyou can do something like the following.

我还要补充一点,您不应该将类传递给<Button />并处理组件本身内部的条件。例如,使用类名库,您可以执行以下操作。

import classnames from 'classnames'

const MyButton = ({children, onClick, type='primary', ...rest }) =>
(
    <button
        onClick   = {onClick}
        {/* 
          depends on the type prop, you will get the relevent button 
          so no need for consumers to care about the internals of the component
        */}
        className = {classnames('.btn', { [`btn-${type}`]: true })}
        {...rest}
    >
        {children}
    </button>
);

You can even combine CSS Modules & classnameslib to create some powerful combinations.

你甚至可以结合 CSS Modules 和classnameslib 来创建一些强大的组合。

回答by David Meents

Personally, I would use global CSS and wire it up with Webpack. It will keep your React much cleaner and of course more modular and easily edited.

就个人而言,我会使用全局 CSS 并将其与 Webpack 连接起来。它会让你的 React 更简洁,当然也更模块化,更容易编辑。

To the best of my knowledge, SCSS features cannot be used inline with your React.

据我所知,SCSS 特性不能与你的 React 一起使用。

If you need to set inline styles in React it's done like this;

如果你需要在 React 中设置内联样式,可以这样做;

var buttonStyle = {
    backgroundColor: "#229ac8",
    backgroundImage: "linear-gradient(to bottom, #23a1d1, #1f90bb)",
    backgroundRepeat: "repeat-x",
    borderColor: "#1f90bb #1f90bb #145e7a",
    color: "#ffffff",
    textShadow: "0 -1px 0 rgba(0, 0, 0, 0.25)"
}
<button style={buttonStyle}>Button</button>

回答by manyrdz

Question 1:

How can I set the button's complete style as inline style?

问题 1:

如何将按钮的完整样式设置为内联样式?

From the official docs:

来自官方文档

In React, inline styles are not specified as a string. Instead they are specified with an object whose key is the camelCased version of the style name, and whose value is the style's value, usually a string

在 React 中,内联样式未指定为字符串。相反,它们使用一个对象指定,该对象的键是样式名称的驼峰式版本,其值是样式的值,通常是一个字符串

Given the following css

鉴于以下css

.btn-primary {
    background-color: #229ac8;
    background-image: linear-gradient(to bottom, #23a1d1, #1f90bb);
    background-repeat: repeat-x;
    border-color: #1f90bb #1f90bb #145e7a;
    color: #ffffff;
    text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
}

An inline style representation of it would be

它的内联样式表示将是

const MyButton = () =>
(
    <button
        className = { {
            backgroundColor: '#229ac8',
            backgroundImage: 'linear-gradient(to bottom, #23a1d1, #1f90bb)',
            backgroundRepeat: 'repeat-x',
            borderColor: '#1f90bb #1f90bb #145e7a',
            color: '#ffffff',
            textShadow: '0 -1px 0 rgba(0, 0, 0, 0.25)'
        } }
    </button>
);

Question 2

Also, can I use some scss features like mixins in react to generate button styles dynamically passing color as variable ?

问题2

另外,我可以在 react 中使用一些 scss 功能(例如 mixins)来生成动态传递颜色作为变量的按钮样式吗?

React's inline style is just an abstraction of css. It has no other fancy features. But since an inline style is just an object, it can be dynamically generated in a way that you can simulate scss mixins and, of course, you can use variables.

React 的内联样式只是对 css 的抽象。它没有其他花哨的功能。但是由于内联样式只是一个对象,因此可以通过模拟 scss mixins 的方式动态生成它,当然,您也可以使用变量。

A scss mixin like this one

像这样的 scss mixin

@mixin border-radius($radius) {
    -webkit-border-radius: $radius;
    -moz-border-radius: $radius;
    -ms-border-radius: $radius;
    border-radius: $radius;
}

Can be accomplished with something like

可以用类似的东西来完成

const borderRadius = ($radius) => {
    return {
        WebkitBorderRadius: $radius;
        MozBorderRadius: $radius;
        MsBorderRadius: $radius;
        borderRadius: $radius;
    }
}

const MyComponent = () => {
    var inlineStyle = Object.assign({}, borderRadius(10), {
        backgroundColor: 'white'
    })

    return (
        <div style={ inlineStyle }>
            Hello, world!
        </div>
    )
}

Question 3

Should I use inline styles or classnames using css in js?

问题 3

我应该在 js 中使用 css 使用内联样式还是类名?

From this one you can't get a definitive answer. But I would recommend use className for generics and inline styles for specifics. Is up to you how to manage the code to meet your needs.

从这个你不能得到一个明确的答案。但我建议将 className 用于泛型,并针对具体情况使用内联样式。取决于您如何管理代码以满足您的需求。

回答by Jaroslav

hover:with using of the hooks:

hover:使用钩子:

const useFade = () => {
  const [ fade, setFade ] = useState(false);

  const onMouseEnter = () => {
    setFade(true);
  };

  const onMouseLeave = () => {
    setFade(false);
  };

  const fadeStyle = !fade ? {
    opacity: 1, transition: 'all .2s ease-in-out',
  } : {
    opacity: .5, transition: 'all .2s ease-in-out',
  };

  return { fadeStyle, onMouseEnter, onMouseLeave };
};

const ListItem = ({ style }) => {
  const { fadeStyle, ...fadeProps } = useFade();

  return (
    <Paper
      style={{...fadeStyle, ...style}}
      {...fadeProps}
    >
      {...}
    </Paper>
  );
};

You can use the same technique for more complex scenarios.

您可以将相同的技术用于更复杂的场景。

回答by Mike S.

You could set a javascript object with inline styles in the button to change the color dynamically. For example:

您可以在按钮中设置带有内联样式的 javascript 对象以动态更改颜色。例如:

const normalButtonStyle = {
  background:'gray',
  color:'black',
  borderColor:'white'
}
const buttonCompleteStyle = {
  background:'red',
  color:'white',
  borderColor:'black'
} // this can be included in from another file as a style object as well

const MyButton = ({children, status, onClick, classNames, ...rest }) =>
(
  <button
    onClick   = {onClick}
    className = {`${classNames}`}
    {...rest}
    style={status === 'complete' ? buttonCompleteStyle : normalButtonStyle}
  >
    {children}
  </button>
);

Not tested, but something like that. Take a look at how Material UIdoes it.

没有测试,但类似的东西。看看Material UI是如何做到的。