javascript - 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
解决方案
它会引发错误,因为预期的语法是带有空格分隔的类名的字符串。
您可以将数组传播到另一个数组或参数列表中,但不能传播到字符串变量中。
您需要用空格连接数组以获取字符串作为输出并将其传递为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(' '));
推荐阅读
- sql - 如何在 sql 中生成非常大的数组
- cassandra - 如何更改 cassandra.yaml 文件并重启 cassandra 集群?
- c++ - 当头文件的文件夹位于同一目录中时检测到包含错误?
- angular - 找不到构建器 @angular-devkit/build-angular:dev-server 的实现
- google-app-engine - 如何在 Google NLP 情感分析中正确训练模型
- javascript - 使用组件内的选择器将主题/样式应用于所有 html/react 标签
- powershell - ConvertFrom-String 返回符号而不是文本
- javascript - 如何在 Angular ace 编辑器中根据特定场景启用和禁用默认代码段关键字
- python - 使用 python 电子邮件库解析原始电子邮件添加不需要的字符
- python - 如何在不指定 excel 名称的情况下从文件夹中读取 excel?