简体   繁体   English

设置复杂反应内联样式,例如悬停,在按钮等反应组件上激活

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

I have the following styles in css for my buttons. 我的按钮在css中有以下样式。 I am also using bootstrap. 我也在使用bootstrap。

.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. 我已经将一个按钮定义为反应中的一个组件。

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 scss features like mixins in react to generate button styles dynamically passing color as variable ? 另外,我可以使用一些scss功能,如react mixins来生成动态传递颜色作为变量的按钮样式吗?

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? 对于像按钮这样的通用组件,我们应该使用一个全局类,它可以在定义按钮的所有位置重用,或者使用本地内联样式并在所有位置创建内联样式?

CSS in JS (with pseudo classes & MQ support) JS中的CSS (具有伪类和MQ支持)

There are lots of libs to write CSS with React that 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很多lib支持伪类但是所有这些都需要你在JS中内联或编写你的CSS 我强烈推荐

CSS Modules (Write your CSS as normal, but in a better way) CSS模块(正常写你的CSS,但以更好的方式)

There is also CSS modules which if you are already using Webpack should be simple to set it up , which let you import / require your 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. 我还要补充一点,你不应该将类传递给<Button />并处理组件内部的条件。 For example using classnames lib you can do something like the following. 例如, 使用类名 lib,您可以执行以下操作。

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 & classnames lib to create some powerful combinations. 您甚至可以组合CSS模块和classnames lib来创建一些强大的组合。

Personally, I would use global CSS and wire it up with Webpack . 就个人而言,我会使用全局CSS并将其与Webpack连接起来 It will keep your React much cleaner and of course more modular and easily edited. 它将使您的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>

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. 对于更复杂的场景,您可以使用相同的技术。

You could set a javascript object with inline styles in the button to change the color dynamically. 您可以在按钮中设置带有内嵌样式的javascript对象,以动态更改颜色。 For example: 例如:

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 UI does it. 看一下Material UI是如何做到的。

Question 1: 问题1:

How can I set the button's complete style as inline style? 如何将按钮的完整样式设置为内联样式?

From the official docs : 来自官方文档

In React, inline styles are not specified as a string. 在React中,内联样式未指定为字符串。 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 相反,它们使用一个对象来指定,该对象的键是样式名称的camelCased版本,其值是样式的值,通常是字符串

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 问题2

Also, can I use some scss features like mixins in react to generate button styles dynamically passing color as variable ? 另外,我可以使用一些scss功能,如反应中的mixins来生成动态传递颜色作为变量的按钮样式吗?

React's inline style is just an abstraction of css. React的内联样式只是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. 但是由于内联样式只是一个对象,它可以以一种可以模拟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 问题3

Should I use inline styles or classnames using css in js? 我应该在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. 但我建议使用className作为特定的泛型和内联样式。 Is up to you how to manage the code to meet your needs. 由您决定如何管理代码以满足您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM