我正在努力研究 JSX。 我发现了一个非常奇怪的行为。 这是我的代码:
const name = undefined;
const myFunc = () => undefined;
let template = (
<div>
{myFunc()}
{name}
{undefined}
</div>
);
ReactDOM.render(template, document.querySelector("#root"));
输出是一次: 未定义
为什么常量“名称”是唯一解析为字符串的未定义值? 这个 const 和其他两个表达式有什么区别? (与 bool 值和空值相同。) 请在此处查看我的代码:codepen
最佳答案
那是因为 JSX
是 React.createElement(component, props, ...children)
的语法糖
它会忽略这些类型(参见 DOCS):
- bool 值
- 未定义
- 无
我刚刚意识到这只发生在像 codepen 这样的一些编辑器上,因为它们在全局上下文和 window.name will always be a string 中运行代码。 .
window.name will convert all values to their string representations by using the toString method.
如果您将变量更改为其他变量,假设 name1
它的行为符合预期。
const name1 = undefined;
const myFunc = function(){return undefined};
let template = (
<div>
{name1}
{undefined}
{myFunc()}
</div>
);
顺便说一下,stack-snippets 的行为是一样的:
console.log('name is ', name);
const name = undefined;
console.log('and now name is ', name);
const name1 = undefined;
const myFunc = function(){return undefined};
let template = (
<div>
{name}
{name1}
{undefined}
{myFunc()}
</div>
);
ReactDOM.render(template, document.querySelector("#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>
codesandbox
或 jsfiddle
等其他编辑器会将代码包装在一个函数中,因此与 window.name
没有冲突。
关于javascript - 为什么只有当它们是变量时,React 才会将 undefined/boolean/null 解析为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52904143/