从React组件转换为使用一个钩子

时间:2020-05-20 16:59:26

标签: javascript reactjs react-hooks

我正在学习React钩子,并想将一个相对简单的组件转换为使用钩子的组件。该组件称为FadeIn,它包装子组件以使其在从父组件传递的transitionDuration中变得可见(使用CSS和不透明度)。以下是我组件的工作代码:

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

export class FadeIn extends Component {
  constructor(props) {
    super(props);
    this.makeVisible = this.makeVisible.bind(this);
    this.state = { opacity: 0.01 };
  }

  componentDidMount() {
    this.makeVisible();
  }

  makeVisible() {
    this.setState({ opacity: 1 });
  }

  render() {
    const { children, transitionDuration } = this.props;
    const { opacity } = this.state;
    return (
      <div
        style={{
          transition: `opacity ${transitionDuration}ms ease-in`,
          opacity,
        }}
      >
        {children}
      </div>
    );
  }
}


FadeIn.defaultProps = {
  transitionDuration: 600,
};

FadeIn.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node,
  ]).isRequired,
  transitionDuration: PropTypes.number,
};

这是我的hooks组件的外观:

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

export const FadeIn = (props) => {
  const [opacity, makeVisible] = useState(0.01);
  const [children, setChildren] = useState(props);
  const [transitionDuration, setTransitionDuration] = useState(props);

  useEffect(() => {
    makeVisible(1);
    setChildren(props);
    setTransitionDuration(props);
  }, [props])



  return (
    <div
      style={{
        transition: `opacity ${transitionDuration}ms ease-in`,
        opacity,
      }}
    >
      {children}
    </div>
  );
}
// }


FadeIn.defaultProps = {
  transitionDuration: 600,
};

FadeIn.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node,
  ]).isRequired,
  transitionDuration: PropTypes.number,
};

我安静了

不变违规:对象作为React子对象无效(发现: 带有键{children,transitionDuration}的对象。如果你想 呈现儿童的集合,请改用数组。

这里是什么问题?

1 个答案:

答案 0 :(得分:2)

您正在将props对象设置为您的状态。您需要从children

获取props.children数组
setChildren(props);

setChildren(props.children);

请记住,这完全没有必要,因为您可以通过访问props.children来呈现子代而无需将其保存为状态

return (
    <div
      style={{
        transition: `opacity ${transitionDuration}ms ease-in`,
        opacity,
      }}
    >
      {props.children}

    </div>
);

您还需要更改

setTransitionDuration(props);

setTransitionDuration(props.transitionDuration);