gpt4 book ai didi

javascript - 从 React 组件转换为使用一个钩子(Hook)

转载 作者:行者123 更新时间:2023-12-04 09:56:11 26 4
gpt4 key购买 nike

我正在学习 React 钩子(Hook),并希望将一个相对简单的组件转换为使用钩子(Hook)的组件。该组件称为 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,
};

这是我的钩子(Hook)组件的样子:
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,
};

我安静了一个与

Invariant Violation: Objects are not valid as a React child (found: object with keys {children, transitionDuration}). If you meant to render a collection of children, use an array instead.



这里有什么问题?

最佳答案

您正在您的状态下设置 Prop 对象。你需要得到children来自 props.children 的数组

setChildren(props);


setChildren(props.children);

请记住,这是完全没有必要的,因为您可以通过访问 props.children 来渲染 child 。没有将它们保存在状态中
return (
<div
style={{
transition: `opacity ${transitionDuration}ms ease-in`,
opacity,
}}
>
{props.children}

</div>
);

你也需要改变
setTransitionDuration(props);


setTransitionDuration(props.transitionDuration);

关于javascript - 从 React 组件转换为使用一个钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61918714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com