加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 为什么React只在它们是变量时将undefined / boolean

发布时间:2020-12-15 20:47:57 所属栏目:百科 来源:网络整理
导读:我正试图围绕JSX. 我发现了一个非常奇怪的行为. 这是我的代码: const name = undefined;const myFunc = () = undefined;let template = ( div {myFunc()} {name} {undefined} /div);ReactDOM.render(template,document.querySelector("#root")); 输出是一次
我正试图围绕JSX.
我发现了一个非常奇怪的行为.
这是我的代码:
const name = undefined;
const myFunc = () => undefined;
let template = (
  <div>
    {myFunc()}
    {name}
    {undefined}
  </div>
);

ReactDOM.render(template,document.querySelector("#root"));

输出是一次:
未定义

为什么const“name”是唯一解析为字符串的未定义值?
这个const和其他两个表达式有什么区别?
(与Boolean和null相同.)
请在此处查看我的代码:codepen

这是因为JSX是 React.createElement(component,props,...children)的语法糖
它将忽略这些类型(见 DOCS):

>布尔值
>未定义
> null

我只是意识到这只发生在像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没有冲突.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读