首页 > 解决方案 > using spread operator in jsx expression

问题描述

I'm not sure why I can't pass a spread array as a value of an attribute in a JSX expression.

The spread operator resolves into a value which is what I believe the JSX expression is expecting: a value after evaluating the expression.

Note that I am trying to spread an array as a value in a button className attribute in my JSX:

....
   render() {
    const {on, className = '', ...props} = this.props
    const btnClassName = [
      className,
      'btn',
      on ? 'btn-on' : 'btn-off',
    ]

    return (
       <button
          className={...btnClassName} // this throws an error
          aria-label="Toggle"
          {...props}
        />
     )
.....

This works as expected: Note that here I am passing an array (after .join() it's items) as a value in a button className attribute in my JSX:

....
   render() {
    const {on, className = '', ...props} = this.props
    const btnClassName = [
      className,
      'btn',
      on ? 'btn-on' : 'btn-off',
    ].join(' ')

    return (
         <button
          className={btnClassName} // this works as expected
          aria-label="Toggle"
          {...props}
        />
    )
.....

Many thanks

标签: javascriptreactjsecmascript-6

解决方案


它会引发错误,因为预期的语法是带有空格分隔的类名的字符串。

您可以将数组传播到另一个数组或参数列表中,但不能传播到字符串变量中。

您需要用空格连接数组以获取字符串作为输出并将其传递为className.

console.log()这可能会产生误导,因为当您将数组与具有相同数组但展开的空格连接时没有区别。

但这仅仅是因为您将数组传播到 的参数列表中console.log(),并且console.log()在打印它们之前将每个参数用空格分隔:

const classes = ['class1', 'class2', 'class3'];

const join = (...args) => args.join(' ');

console.log(...classes); // console.log() joins the arguments with a space automatically
console.log(join(...classes));
console.log(classes.join(' '));


推荐阅读