我正在学习 reactJs 并尝试将属性传递给组件。
代码如下-
import React from 'react';
import ReactDOM from 'react-dom';
class myComponent extends React.Component {
render() {
if (this.props.signedIn == false) {
return <h1>Hi</h1>;
}
return <h1>Hello!</h1>;
}
}
ReactDOM.render(
<myComponent signedIn={false} />,
document.getElementById('app')
);
这行得通,但请注意我必须注入(inject) false 的部分,因为 javascript 包裹在花括号中。
我怀疑 JSX 是否不像普通 JS 那样将“false”字符串识别为假值?
询问的原因- 与隐藏元素的 ng-show="false"进行比较,但正如评论中所讨论的那样,这可能是因为 ng-show 指令手动将 'false' 评估为假值。
最佳答案
不要忘记修复组件名称,it should start with uppercase letters .
如其他评论和答案中所述,条件与
JSX
无关。这就是 JavaScript 的工作原理。
请注意,重要的事情要记住:
永远不要做双等号 (==
) a.k.a "Abstract Equality"针对 bool 值,这是在寻找错误。
因为引擎只会对 bool 值进行类型强制,这可能会导致意外行为。
例如,
if(2 == true) //returns false
和
if(2 == false) // returns false
来自 spec :
If Type(x) is Boolean, return the result of the comparison ! ToNumber(x) == y.
If Type(y) is Boolean, return the result of the comparison x == ! ToNumber(y).
相反,您可以进行隐式检查:
if (this.props.signedIn)
或显式检查但使用三重等于 a.k.a "strict equality"
if (this.props.signedIn === false)
至于
react
部分:同样,毕竟它基本上只是JavaScript函数和对象。如果您没有传递
prop
,那么它将是 undefined
:
this.props.signedIn // signedIn will be undefined if we didn't pass it as a prop
所以,像上面提到的隐式检查:
if (this.props.signedIn)
会工作得很好。
不传递 prop 的运行示例:
class MyComponent extends React.Component {
render() {
if (this.props.signedIn) {
return <h1>Hi</h1>;
}
return <h1>not signed on!</h1>;
}
}
ReactDOM.render(
<MyComponent />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
运行带有 false
的例子:
class MyComponent extends React.Component {
render() {
if (this.props.signedIn) {
return <h1>Hi</h1>;
}
return <h1>not signed on!</h1>;
}
}
ReactDOM.render(
<MyComponent signedIn={false}/>,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
传入true
的运行示例:
class MyComponent extends React.Component {
render() {
if (this.props.signedIn) {
return <h1>Hi</h1>;
}
return <h1>not signed on!</h1>;
}
}
ReactDOM.render(
<MyComponent signedIn={true}/>,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
关于javascript - JSX 中的虚假值 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48032855/