我该如何编写此类组件来对功能组件做出反应?

时间:2020-03-10 13:34:20

标签: javascript reactjs function

我正在尝试编写我的组件以响应功能,但是我无法对其进行正确的格式化,并且我的类和样式也添加了它,这是转换此组件的正确方法是什么。我所有其他代码都具有功能,我也希望它是一个功能组件

我的组件

import React, { Component } from 'react';
import PropTypes from 'prop-types';

import Tab from './Tab';

class Tabs extends Component {
  static propTypes = {
    children: PropTypes.instanceOf(Array).isRequired,
  }

  constructor(props) {
    super(props);

    this.state = {
      activeTab: this.props.children[0].props.label,
    };
  }

  onClickTabItem = (tab) => {
    this.setState({ activeTab: tab });
  }

  render() {
    const {
      onClickTabItem,
      props: {
        children,
      },
      state: {
        activeTab,
      }
    } = this;

    return (
      <div className="tabs">
        <ol className="tab-list">
          {children.map((child) => {
            const { label } = child.props;

            return (
              <Tab
                activeTab={activeTab}
                key={label}
                label={label}
                onClick={onClickTabItem}
              />
            );
          })}
        </ol>
        <div className="tab-content">
          {children.map((child) => {
            if (child.props.label !== activeTab) return undefined;
            return child.props.children;
          })}
        </div>
      </div>
    );
  }
}

export default Tabs;

2 个答案:

答案 0 :(得分:0)

Checkpoint directory does not exist: file:/opt/spark/.../rdd-541

答案 1 :(得分:0)

因此,您要删除的是renderconstructor,因为它们在功能组件中都不是renderconstructor,接下来要做的是使用useState钩子来维护状态变量。此外,您可以从传递给组件的children中抽出props,对于函数的静态属性,可以在函数本身上声明它们而不是使用static propTypes而是使用Tabs.propTypes

        import React from "react";
        import PropTypes from "prop-types";

        import Tab from "./Tab";

        const Tabs = props => {


          const { children } = props;

          const [state, setState] = useState({
            activeTab: props.children[0].props.label
          });

          const onClickTabItem = tab => {
            setState({ activeTab: tab });
          };

          return (
            <div className='tabs'>
              <ol className='tab-list'>
                {children.map(child => {
                  const { label } = child.props;

                  return (
                    <Tab
                      activeTab={state.activeTab}
                      key={label}
                      label={label}
                      onClick={()=>onClickTabItem()}
                    />
                  );
                })}
              </ol>
              <div className='tab-content'>
                {children.map(child => {
                  if (child.props.label !== activeTab) return undefined;
                  return child.props.children;
                })}
              </div>
            </div>
          );
        };
   //Static Props
     Tabs.propTypes = {
        children: PropTypes.instanceOf(Array).isRequired
      };


    export default Tabs;