熟悉 React 的人, 在接触 Taro 时需要知道的事情。
以下面的组件为例:
export default function MyComponents(props) {
return (
<View>
{/* 条件编译 */}
{!!props.titleVisible && (
<View className="title">
<Text>title</Text>
</View>
)}
{/* 列表渲染 */}
{props.list.map((i) => (
<View key={i.id}>{i.value}</View>
))}
{/* 自定义组件 */}
<CustomComponent something={props.something} />
</View>
);
}
JSX 并不是什么魔法,Babel、Typescript 转译器会将 JSX 转换为函数调用:
function MyComponents(props) {
return React.createElement(
View,
null,
!!props.titleVisible &&
React.createElement(
View,
{
className: 'title',
},
React.createElement(Text, null, 'title')
),
props.list.map((i) =>
React.createElement(
View,
{
key: i.id,
},
i.value
)
),
React.createElement(CustomComponent, {
something: props.something,
})
);
}
JSX 在 React 中会翻译为 React.createElement(type, props, ...children)
。也就是说 JSX 只不过是语法糖,支持任何合法的 JavaScript 表达式,你可以非常灵活地组装它:
function Hello() {
const list = [];
let Wrapper;
if (something) {
list.push(<View>xx</View>);
Wrapper = XXWraper;
} else {
list.push(<Text>yy</Text>);
Wrapper = YYWraper;
}
return (
<View>
<Wrapper>{list}</Wrapper>
</View>
);
}