使用 JavaScript 表达式
你可以任意地在 JSX 当中使用 JavaScript 表达式,在 JSX 当中的表达式要包含在大括号里。例如,在这个 JSX 中:
<MyComponent foo={1 + 2 + 3 + 4} />
对于 MyComponent 来说, props.foo 的值为 10,这是 1 + 2 + 3 + 4 表达式计算得出的。
if 语句和 for 循环在 JavaScript 中不是表达式,因此它们不能直接在 JSX 中使用,所以你可以将它们放在周围的代码中。
import Taro, { Component } from '@tarojs/taro'class App extends Components {render () {let descriptionif (this.props.number % 2 == 0) {description = <Text>even</Text>} else {description = <Text>odd</Text>}return <View>{this.props.number} is an {description} number</View>}}
字符串常量
你可以将字符串常量作为属性值传递。下面这两个 JSX 表达式是等价的:
<MyComponent message="hello world" /><MyComponent message={'hello world'} />
默认为 True
如果你没有给属性传值,它默认为 true。因此下面两个 JSX 是等价的:
<MyTextBox autocomplete /><MyTextBox autocomplete={true} />
和 React/Nerv 的不同: React 可以使用
...拓展操作符来传递属性,但在 Taro 中你不能这么做。例如:
const props = {firstName: 'Plus', lastName: 'Second'}return <Greeting {...props} />
这样的操作会报错。你只能手动地把所有需要引用的 props 写上去:
<Greeting firstName="Plus" lastName="Second" />
嵌套
如果 JSX 标签是闭合式的,那么你需要在结尾处用 />, 就好像 XML/HTML 一样:
const element = <Image src={user.avatarUrl} />;
JSX 标签同样可以相互嵌套:
const element = (<View><Text>Hello!</Text><Text>Good to see you here.</Text></View>)
JavaScript 表达式也可以嵌套:
render () {const todos = ['finish doc', 'submit pr', 'nag dan to review'];return (<ul>{todos.map((todo) => <Text>{todo}</Text>)}</ul>)}
布尔值、Null 和 Undefined 被忽略
false、null、undefined 和 true 都是有效的 children,但它们不会直接被渲染。下面的表达式是等价的:
<View /><View></View><View>{false}</View><View>{null}</View><View>{undefined}</View><View>{true}</View>
这在根据条件来确定是否渲染 元素时非常有用。
以下的 JSX 只会在 showHeader 为 true 时渲染 <Header /> 组件。
<View>{showHeader && <Header />}<Content /></View>
