首页 > 解决方案 > 在反应中将多个返回从类组件转换为功能组件

问题描述

我正在尝试将基于反应本机的类转换为基于函数的类,并且我遇到了一个具有 2 个返回语句的类组件,我不知道如何将其转换为函数组件。这是类组件。请注意,我省略了不重要的代码

    export default class Card extends Component {
  static defaultProps = {
    shadow: true,
    border: true,
    title: null,
  }

  renderHeader = () => {
    const { title } = this.props;
    if (!title) return null;

    return (
      <Block row space="between" style={styles.header}>
        <Text caption>{title}</Text>
        <TouchableOpacity>
          {/* <Icon options /> */}
        </TouchableOpacity>
      </Block>
    )
  }

  render() {
    const { shadow, border, style, children, ...props } = this.props;
    const cardStyles = [
      styles.card,
      shadow && styles.shadow,
      border && styles.border,
      style,
    ];

    return (
      <Block style={cardStyles} {...props}>
        {this.renderHeader()}
        {children}
      </Block>
    )
  }
}

这就是我想出的

const Card = title => {
  static defaultProps = {
    shadow: true,
    border: true,
    title: null,
  }

  renderHeader = () => {
    const { title } = title;
    if (!title) return null;
  }
  renderHeader = () => {
    const { title } = this.props;
    if (!title) return null;
  }
  const { shadow, border, style, children, ...props } = this.props;
  const cardStyles = [
    styles.card,
    shadow && styles.shadow,
    border && styles.border,
    style,
  ];

  return [
    <Block row space="between" style={styles.header}>
        <Text caption>{title}</Text>
        <TouchableOpacity>
          {/* <Icon options /> */}
        </TouchableOpacity>
      </Block> <
    Block style = { cardStyles } { ...props } > { renderHeader() } { children } <
    /Block>
  ]
}

请注意,当我运行代码时,它没有显示任何错误,还请注意,在问这个问题之前,我已经浏览了这里和搜索引擎,但没有找到任何合适的答案

标签: javascriptreactjsreact-nativefunction

解决方案


所有功能组件都有一个参数 prop object 。所以我们可以解构并分配默认值。所以你的代码

 static defaultProps = {
    shadow: true,
    border: true,
    title: null,
  }

现在改为

const Card = ({
  shadow = true,
  border = true,
  title = null,
  style,
  children,
  ...props
}) => {

类组件中的方法变为功能组件中的函数。所以你可以改变你renderHeader

const renderHeader = () => {
    .... 
  };

由于您的 renderHeader 只是另一个函数,因此您可以this在调用它时删除

 {renderHeader()}

转换组件

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;

参考

对象解构


推荐阅读