如何将含多个return语句的React Native类组件转换为函数组件
React Native类组件转函数组件解决方案
现有代码的问题
- 函数组件参数接收错误:未正确接收props对象,直接将第一个参数命名为
title无法拿到其他属性 - 不存在
this关键字:函数组件没有类组件的this实例,所有this.props调用都是无效的 renderHeader方法重复定义且逻辑不完整:两次覆盖定义renderHeader,且定义逻辑缺失完整的头部JSX返回- 输出结构错误:原类组件外层是统一的
Block容器包裹头部和子元素,转换后的代码返回数组将头部和外层容器并列,结构完全不符合原逻辑 static defaultProps用法错误:函数组件不能直接在函数内部写static关键字声明默认属性,需要挂载到函数对象上,或者直接使用参数默认值
正确转换后的代码
推荐使用函数组件更常用的参数默认值写法:
const Card = ({ shadow = true, border = true, title = null, style, children, ...props }) => { const renderHeader = () => { if (!title) return null; return ( <Block row space="between" style={styles.header}> <Text caption>{title}</Text> <TouchableOpacity> {/* <Icon options /> */} </TouchableOpacity> </Block> ) } const cardStyles = [ styles.card, shadow && styles.shadow, border && styles.border, style, ]; return ( <Block style={cardStyles} {...props}> {renderHeader()} {children} </Block> ) } export default Card;
如果需要保留defaultProps的写法可以使用以下版本:
const Card = (props) => { const { shadow, border, title, style, children, ...restProps } = props; const renderHeader = () => { if (!title) return null; return ( <Block row space="between" style={styles.header}> <Text caption>{title}</Text> <TouchableOpacity> {/* <Icon options /> */} </TouchableOpacity> </Block> ) } const cardStyles = [ styles.card, shadow && styles.shadow, border && styles.border, style, ]; return ( <Block style={cardStyles} {...restProps}> {renderHeader()} {children} </Block> ) } Card.defaultProps = { shadow: true, border: true, title: null, } export default Card;
内容的提问来源于stack exchange,提问作者gbenga ogunbule
相关产品推荐
相关产品推荐

