ReactJs中的AND运算符

ReactJs中的AND运算符,reactjs,and-operator,Reactjs,And Operator,使用AND运算符计算第6行中的表达式时 1. export default function App() { 2. var isDone = false; 3. const strikethrough = { textDecoration: "line-through" }; 4. return ( 5. <div className="App"> 6. <h1 style={isDone && st

使用AND运算符计算第6行中的表达式时

1. export default function App() {
2.  var isDone = false;
3.  const strikethrough = { textDecoration: "line-through" };
4.  return (
5.    <div className="App">
6.      <h1 style={isDone && strikethrough}>Hello CodeSandbox</h1>
7.    </div>
8.   );
9. }
这会产生一个错误,即“必须仅为JSX属性分配一个非空表达式”

我正在学习一门在线课程。这里发生了什么事?

试着记录你的病情

您应该具有以下代码:

VS

问题是您的
风格
道具不接受布尔值

更多

如果您使用的是
typescript
,您可以检查
h1
标签的
props

有一个
className?:字符串它的意思是字符串或无


因此,您不能从
isDone&&strikethrough
传递布尔值(返回false)。

您不能分配非空表达式,因为您已经计算出来了。所以你需要做一些类似的事情

<h1 style={isDone ? strikethrough : {}}>Hello CodeSandbox</h1>
Hello-CodeSandbox

为了有一个默认的样式。

尝试
style={isDone?删除线:{}
是的,我尝试了Hello CodeSandbox,这很好,但是为什么在这种情况下,&&操作符不能按预期工作呢?这是因为
&&
是这样工作的。如果
&&
之前的内容是真实的,那么它将返回
&&
之后的内容。如果
&&
之前的内容是falsy,它将返回第一个值。这通常是
false
。你的情况就是这样。当条件为false时,它返回false并被指定给样式attribute@TheAlpha93谢谢你的解释。非常感谢,这个解释对我帮助很大。我确实记录了情况以了解情况
const isDone = true
const strikethrough = 'yes' // or { textDecoration: "line-through" }

console.log(isDone && strikethrough) // return 'yes'
const isDone = false
const strikethrough = 'yes'

console.log(isDone && strikethrough) // return boolean false
<h1 style={isDone ? strikethrough : {}}>Hello CodeSandbox</h1>