2017-06-02 74 views
0

我的JSX文件是满的:如何摆脱JSX中的“className”属性?

<div className="...">...</div> 

例如:

const Page =() => (

    <div className="Page"> 

    <div className="sideMenu"> 
     <Route path="/" component={SidemenuMainCont} /> 
    </div> 

    <div className="mainColumn"> 
     <div className="header"> 
     <Header /> 
     </div> 
     <div className="section"> 
     <Route path="/" component={TenCont} /> 
     </div> 
     <div className="footer"> 
     <Footer /> 
     </div> 
    </div> 

    <AuthLoginModalCont /> 

    </div> 

); 

此代码看起来因为这个有线。 “className”对于重复使用的属性来说太长。有没有任何常见的做法来摆脱这种烦人的重复?或者缩短它?

我可以做一个自定义组件是这样的:

<Div cl="...">...</Div> 

但我有兴趣,如果有一个常见的做法。也许已经有一个className属性的别名?或者以其他方式设置CSS类名称。

UPDATE

感谢,普热扎莱夫斯基一个有趣的想法。但实际上我正在使用CSS模块。所以,我的代码是:

import S from "./_.scss"; 
... 
<div className={S.Page}>...</div> 

而且它不工作:

<Styled {S.Page}>...</Styled> 

回答

1

你可以为它编写一个Babel插件 - 例如, babel-plugin-react-html-attrs允许您在使用React中的JSX时使用classfor属性,并将它们更改为classNamehtmlFor属性(JSX属性是对象文字的语法糖)。在转换JSX时需要React。

下面是一个通天6插件transpiling时会改变cl属性className完整的源代码:

var TRANSLATIONS = { 
    'cl': 'className' 
} 

module.exports = function() { 
    return { 
    visitor: { 
     JSXAttribute: function(node) { 
     if (node.node.name.name in TRANSLATIONS) { 
      node.node.name.name = TRANSLATIONS[node.node.name.name] 
     } 
     } 
    } 
    } 
} 

我的实际建议只是坚持className,你会习惯它: )

+1

为什么地球上他们没有把这个写入JSX transpiler开始...... – djvs

1

你可以这样说:

class Div extends React.Component { 
     render() { 
      return (
       <div className={this.props.cl} > 
        {this.props.children} 
       </div> 
      ); 
     } 
    }; 
    export default Div; 

并使用

<Div cl="my_class"></Div> 
+0

看来OP已经知道这个选项。 –

0

你应该考虑使用简单的Styled组件fo r处理所有真布尔属性作为类名称并使用classnames将它们作为字符串加入的情况。

class Styled extends React.PureComponent { 
    render() { 
     const { children, tag: Tag = 'div', ...rest } = this.props; 
     const [booleans, others] = partition(x => x === true)(rest) 

     return (
      <Tag 
       className={classNames(booleans)} 
       {...others} 
      > 
       {children} 
      </Tag> 
     ) 
    } 
} 

const Page =() => (
    <Styled Page> 

    <Styled sideMenu> 
     <Route path="/" component={SidemenuMainCont} /> 
    </Styled> 

    <Styled mainColumn> 
     <Styled Header> 
     <Header /> 
     </Styled> 
     <Styled section tag="section"> 
     <Route path="/" component={TenCont} /> 
     </Styled section> 
     <Styled footer tag="footer"> 
     <Footer /> 
     </Styled> 
    </Styled> 

    <AuthLoginModalCont /> 

    </Styled> 
); 

a slight variation of the idea与使用Proxy对象。但是,由于它不能完全填充,所以它会在较老的JS引擎上中断,但是允许在没有事先声明MainColumn的情况下编写<styled.MainColumn full-width red>,并且在保留全名时更容易调试React Developer Tools