开发者问题收集

Reactjs TypeError:无法读取未定义的属性“style”

2018-11-03
6558

如何解释以下错误?

TypeError: Cannot read property 'style' of undefined

import React from 'react';
import PropTypes from 'prop-types';
import {VelocityComponent} from 'velocity-react';
import 'velocity-animate/velocity.ui';

const FuseAnimate = (props) => {
    const children = React.cloneElement(props.children, {
        style: { // this line throws the error
            ...props.children.style,
            visibility: 'hidden'
        }
    });
    return (
        <VelocityComponent {...props} children={children}/>
    )

};

FuseAnimate.propTypes = {
    children: PropTypes.element.isRequired
};

FuseAnimate.defaultProps = {
    animation          : 'transition.fadeIn',
    runOnMount         : true,
    targetQuerySelector: null,
    interruptBehavior  : 'stop',
    visibility         : 'visible',
    duration           : 300,
    delay              : 50,
    easing             : [0.4, 0.0, 0.2, 1],
    display            : null
};

export default FuseAnimate;
1个回答

我相信 ...props.children.style 是错误的根源。如果您执行的操作类似于...

render() {
  <FuseAnimate /> // no children
}

props.children 将未定义。

Tom Coughlin
2018-11-03