ReactJs 中的 AND 运算符

IT技术 reactjs and-operator
2021-05-13 15:15:35

在使用 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. }

什么时候isDone = false,我收到一个错误

' styleprop 需要从样式属性到值的映射,而不是字符串。例如,使用 JSX 时,style={‌{marginRight:spacing + 'em'}}。

isDone = true,一切正常。

不知何故,null 不起作用,为了检查这一点,我使用了以下内容

<h1 style={}>Hello CodeSandbox</h1>

这给出了一个错误,即“JSX 属性只能被分配一个非空表达式”

我正在从在线课程中学习 ReactJs。这里发生了什么事?

2个回答

尝试控制台记录您的情况。

你应该有这个代码:

<h1 style={isDone ? strikethrough : undefined}>

或者

<h1 style={isDone ? strikethrough : {}}>

const isDone = true
const strikethrough = 'yes' // or { textDecoration: "line-through" }

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

VS

const isDone = false
const strikethrough = 'yes'

console.log(isDone && strikethrough) // return boolean false

问题是您的styleprops不接受布尔值

更多的。

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

有一种className?: string;意思string or nothing

所以,你不能传递布尔有isDone && strikethrough(返回false)。

正如您已经发现的那样,您不能分配非空表达式。所以你需要做类似的事情

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

以获得默认样式。