是否允许在JavaScript中添加React-JSX代码块?附渲染函数问题
当然可以在JavaScript中使用React JSX代码块!
不过你的代码里有几个关键问题需要修正,我帮你一步步梳理:
首先是低级拼写错误
你的渲染方法名写成了reder,React组件的标准渲染方法名是**render**,这个拼写错误会直接导致组件无法正常渲染。
核心问题:JSX不能用+=拼接
JSX本质是React.createElement()的语法糖,最终会被转换成React元素对象,而不是普通字符串。直接用+=拼接JSX元素,会导致对象和对象/字符串强行拼接,最终输出[object Object]这类无效内容,完全达不到你想要的渲染效果。
两种正确的实现方式
下面是React推荐的两种写法,都能实现你想要的条件渲染效果:
方法1:用数组存储元素
class AwesomeTestClass extends React.Component { constructor() { super(); // ES6类继承必须调用super() /* constructor逻辑 */ } render() { // 修正拼写 const contentElements = [ <Text key="basic-text"> basic text 1 </Text> ]; if (someCondition) { contentElements.push(<Text key="condition-text"> add some condition text </Text>); } else { contentElements.push(<Text key="else-text"> add other condition text </Text>); } contentElements.push(<Text key="end-text"> end of awesome text </Text>); return ( <View> {contentElements} </View> ); } }
方法2:直接在JSX中嵌入条件表达式
这种写法更简洁,也是React项目中最常用的条件渲染方式:
class AwesomeTestClass extends React.Component { constructor() { super(); /* constructor逻辑 */ } render() { return ( <View> <Text> basic text 1 </Text> {/* 直接在JSX里写三元表达式做判断 */} {someCondition ? ( <Text> add some condition text </Text> ) : ( <Text> add other condition text </Text> )} <Text> end of awesome text </Text> </View> ); } }
额外注意点
- 自定义组件必须继承
React.Component(或React.PureComponent),否则React无法识别它为可渲染组件; - 类组件的构造函数里必须调用
super(),这是ES6类继承的强制要求; - 用数组存储JSX元素时,每个元素需要设置唯一的
key属性,帮助React高效更新DOM。
修改后你的组件就能正确渲染出预期的内容啦!
内容的提问来源于stack exchange,提问作者TessavWalstijn
相关产品推荐
相关产品推荐

