【问题标题】:How to add hover css style with React.createElement如何使用 React.createElement 添加悬停 CSS 样式
【发布时间】:2022-01-20 00:48:45
【问题描述】:

我正在使用React.createElement 创建一个按钮:

React.createElement('button', {style: button.key === this.state.customBtnSelected ? customBtnSelected : customBtnUnSelected, onClick: () => {this.handleCustomBtnClick(i)} }, button.label)

所以其中一种 css 样式在 customBtnUnSelected 变量中。

但是如何为 hover 状态添加 css 类? 到目前为止,这不起作用:

       const customBtnUnSelected = {
        padding: 12,
        textAlign: "center",
        textDecoration: "none",
        display: "inline-block",
        fontSize: 12, 
        cursor: "pointer",
        backgroundColor: "#CFD4DA",
        border: "1px solid white",
        &:hover: {
          color: "#fff"
        }
      };

【问题讨论】:

    标签: javascript css reactjs


    【解决方案1】:

    不能使用内联样式对元素使用 :hover、:after 或 :before 样式。

    实现这一目标的唯一方法是使用<style> 标记,或将外部CSS 文件链接到您的项目。

    要插入样式标签,只需将其放置在应用中的某个位置即可。它可能在您的某个组件中,或者在根 HTMl 文件中,等等...

    return (
      <style>{`
        .myButton {
          padding: 8;
          background: black
        }
        .myButton:hover {
          background: grey
        }
      `}</style>
    )
    

    然后,您可以在按钮的 className 属性上使用 myButton 类。

    <button className='myButton'>Click</button>
    

    React.createElement('button', {className: 'myButton'})
    

    【讨论】:

      【解决方案2】:

      无论使用 React.createElement 还是 JSX 语法,React 都不支持选择具有内联样式的伪元素。

      这个问题有一些答案和更多可能对您有所帮助的提示: CSS pseudo elements in React

      【讨论】:

        猜你喜欢
        • 2020-02-14
        • 2017-04-03
        • 2020-01-21
        • 2012-09-26
        • 1970-01-01
        • 2012-08-25
        • 2016-07-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多