How can I deal with a long className in React JSX?

谁说胖子不能爱 提交于 2019-12-23 09:38:05

问题


Let's say I'm rendering this component in React JSX:

render() {
  return (
    <h1 className="col-xs-6 col-xs-offset-3 col-md-4 col-md-offset-4 col-lg-2 col-lg-offset-5">Some text</h1>
  );
}

The classes trigger my JS linter as a line that's too long, and it's very hard to read. How can I separate a long className property in a React component into multiple lines without breaking JSX syntax or triggering a different error in a JS linter? (I'm using ESLint).


回答1:


Another Cleaner method will be to store the classNames in an array and join them.

render() { const classNames = ['col-xs-6', 'col-xs-offset-3', 'col-md-4', 'col-md-offset-4', 'col-lg-2', 'col-lg-offset-5'] return ( <h1 className={classNames.join(' ')}>Some text</h1> ); }




回答2:


I usually just wrap the strings to multiple lines and concatenate them. Don't forget to add spaces at the end or beginning of the strings.

So for your example it would be:

render() {
 return (
  <h1 className={
   'col-xs-6 ' +
   'col-xs-offset-3 ' +
   'col-md-4 ' +
   'col-md-offset-4 ' +
   'col-lg-2 ' +
   'col-lg-offset-5'}>Some text</h1>
 );
}

This way you it's also way easier to scan which classNames you have set.

Here is a great resource for some best-practice coding patterns, together with their respective ESLint or JSCS option.




回答3:


@Imamudin Naseem solution with some code style improvements

I would suggest to improve code style and save classNames directly as a string

render() {
  const classNames = [
     'col-xs-6',
     'col-xs-offset-3',
     'col-md-4',
     'col-md-offset-4',
     'col-lg-2',
     'col-lg-offset-5'
  ].join(' ')

  return (
    <h1 className={classNames}>
      Some text
    </h1>
  );
}



回答4:


You can also use classNames:

classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''

Maybe you can define some of your classes as variable, and reuse it.




回答5:


I would suggest if there is some logic (decided based on some other values/props) to how the entire classname is decided you should use the classNames npm package.

However, in your case it seems that the class list is known to you already. In such a case, I tend to use Javascript template literals which allow a string to be split across multiple lines. Like this:

render() {
    return (
        <h1 className={`col-xs-6 col-xs-offset-3 col-md-4 col-md-offset-4 
            col-lg-2 col-lg-offset-5`}
        >
            Some text
        </h1>
    );
}


来源:https://stackoverflow.com/questions/36678059/how-can-i-deal-with-a-long-classname-in-react-jsx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!