函数式组件报错
-
React is not defined
//SplitPane.jsx import Taro from '@tarojs/taro'; import {View} from '@tarojs/components'; export default function SplitPane(props) { return ( <View className='SplitPane'> <View className='SplitPane-left'> {props.left} </View> <View className='SplitPane-right'> {props.right} </View> </View> ); }
和
// list.jsx import Taro, {Component} from '@tarojs/taro'; import {View, Button, Text} from '@tarojs/components'; import {connect} from '@tarojs/redux'; import {add, minus, asyncAdd} from '../../actions/counter'; import SplitPane from "./component/SplitPane" // import './index.scss'; @connect ( ({counter}) => ({ counter, }), dispatch => ({ add () { dispatch (add ()); }, dec () { dispatch (minus ()); }, asyncAdd () { dispatch (asyncAdd ()); }, }) ) class Index extends Component { config = { navigationBarTitleText: 'List', }; render () { return ( <View className='index'> <SplitPane left={ <Text>Left</Text> } right={ <Text>Right</Text> } /> <Button className='add_btn' onClick={()=>{Taro.navigateTo({url: '/pages/list/list'})}}>跳转list</Button> <Button className='add_btn' onClick={this.props.add}>+</Button> <Button className='dec_btn' onClick={this.props.dec}>-</Button> <Button className='dec_btn' onClick={this.props.asyncAdd}>async</Button> <View><Text>{this.props.counter.num}</Text></View> <View><Text>Hello, World</Text></View> </View> ); } } export default Index;
-
基本信息
-
这个问题是因为小程序的模板语法跟jsx语法的根本差异造成的,官网文档有写这个注意事项,但没说明这个错误信息Children 与组合 · Taro
对于本题,正确写法应该是在SplitPane.jsx里:<!-- 其他代码 --> <View className='SplitPane-left'> {props.renderLeft} </View> <View className='SplitPane-right'> {props.renderRight} </View> <!-- 其他代码 -->
在list.jsx中:
<!-- 其他代码 --> <SplitPane left={ <Text>Left</Text> } right={ <Text>Right</Text> } /> <!-- 其他代码 -->
-
相关的坑:
-
列表列表不能在循环中使用render函数:
- 类似需求:创建列表,封装列表项的布局,对外部组件提供仅对每一项的模板渲染,类似vue中的作用域插槽
-
<!-- 不能在组件中使用类似以下的写法,会报一堆错 --> <View> {list.map((item, index) => <View item={item} key={index}>{props.renderListItem(item)}</View>)} </View>
这个也是小程序模板跟jsx差异造成的问题——微信小程序中会报错,h5环境正常,其他环境没试过
-
-
@yang023 谢谢啦!真是救命了