对象无效,因为找到了React子对象:带有键{paddingTop,paddingBottom}的对象?

时间:2018-03-17 09:59:06

标签: javascript reactjs react-router

当我尝试设置component样式时,我收到此错误:

invariant.js?d8db:42 Uncaught Error: Objects are not valid as a React child (found: object with keys {paddingTop, paddingBottom}). If you meant to render a collection of children, use an array instead.
    in div (created by Article)
    in div (created by Article)
    in Article (created by Articlelist)
    in div (created by Articlelist)
    in Articlelist (created by App)
    in div (created by App)
    in App
    at invariant (invariant.js?d8db:42)
    at throwOnInvalidObjectType (react-dom.development.js?61bb:6748)
    at createChild (react-dom.development.js?61bb:7012)
    at reconcileChildrenArray (react-dom.development.js?61bb:7282)
    at reconcileChildFibers (react-dom.development.js?61bb:7651)
    at reconcileChildrenAtExpirationTime (react-dom.development.js?61bb:7756)
    at reconcileChildren (react-dom.development.js?61bb:7747)
    at updateHostComponent (react-dom.development.js?61bb:7998)
    at beginWork (react-dom.development.js?61bb:8229)
    at performUnitOfWork (react-dom.development.js?61bb:10224)

这是我的组件:

import React, {Component} from 'react';
import PropTypes from 'prop-types';
const styles = {
    article: {
        paddingBottom: 10,
        borderBottomStyle: 'solid',
        borderBottomColor: '#aaa',
        borderBottomWidth: 1,
        marginBottom: 10,
    },
    title: {
        fontWeight: 'bold',
    },
    date: {
        fontSize: '0.8em',
        color: '#888',
    },
    author: {
        paddingTop: 10,
        paddingBottom: 10,
    },
    body: {
        paddingLeft: 20,
    }
};
class Article extends Component {
    render() {
        return (
            <div style={styles.article}>
                <div style={styles.title}>{this.props.article.title}</div>
                <div style={styles.date}>{this.props.article.date}</div>
                <div >style={styles.author}
                    <a  href={this.props.author.website}>
                        {this.props.author.firstName}-{this.props.author.lastName}
                    </a>

                </div>
                <div style={styles.body}>{this.props.article.body}</div>
            </div>
        );
    }
}


export default Article;

我的错误截图:

enter image description here

我可以像这样设计我的组件吗?我知道还有另一种方法可以使用className来设置组件的样式。但我不想使用那种方法。你能告诉我为什么会收到这个错误吗? 我可以使用这种方法吗?

1 个答案:

答案 0 :(得分:0)

您未在此处正确关闭div代码:

<div >style={styles.author}

由于这种反应,请将styles.author视为孩子,而不是style,这不是有效的孩子。

将其更改为

<div style={styles.author}>