JSX不会将表达式中的整数计算为布尔值

时间:2016-06-01 11:06:25

标签: reactjs react-jsx conditional-operator jsx

我习惯写这样的渲染可选组件:

cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
project("My Project")

set(CMAKE_CXX_FLAGS "-std=c++11")
# Set cmake prefix path to enable cmake to find freenect2
set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} $ENV{HOME}/freenect2/lib/cmake/freenect2)
find_package(freenect2 REQUIRED)

include_directories("/usr/include/libusb-1.0/")

INCLUDE_DIRECTORIES(
  ${freenect2_INCLUDE_DIR}
)

add_executable(main ./main.cpp)

target_link_libraries(main ${freenect2_LIBRARIES})

if/else in JSX guide中提到了这个简写var Foo = React.createClass({ render: function() { var length = 0; return <div>Foo {length && <Bar />}</div>; } }); 作为立即调用的函数表达式。但是,自从我最新的React更新后,它开始呈现if而不是0

Here is a jsfiddle

为什么会这样?

2 个答案:

答案 0 :(得分:5)

&&运算符首先计算左侧表达式,如果左侧表达式计算为falsy,则返回左侧表达式的值而不进一步计算。

因此(0 && "Bar")计算为0,然后呈现为字符串。如果在渲染中丢弃了所有虚假值,则无法在React中打印0,例如length is { 0 }只会打印length is

但是falsenullundefined会被React渲染器用作儿童,并且它是exactly for this use case

length is { 0 } // length is 0
length is { NaN} // length is NaN
length is { null } // length is
length is { false } // length is
length is { undefined } // length is

你需要你的&&运算符的左手表达式来返回这三个中的一个,最简单的是布尔值:

( !!length && "Bar" ) // evaluates to false, doesn't print
( (length > 0) && "Bar" ) // evaluates to false, doesn't print
( (length != 0) && "Bar" ) // evaluates to false, doesn't print
( Boolean(length) && "Bar" ) // evaluates to false, doesn't print

答案 1 :(得分:1)

我会像

那样写

length ? <Bar /> : void(0)

React不会呈现undefined的内容,而void(0)则保证不会有任何库更改undefined的值