无法将其他道具传递给{this.props.children}

时间:2019-12-14 08:14:22

标签: reactjs jsx next.js

我是React的新手,我想将某个参数作为props传递给我的Layout Component(它是父组件)中的{this.props.children}。我使用React.cloneElement尝试了此操作,但它返回一个错误“ React.cloneElement(...):参数必须是React元素,但您传递了null”。即使它只适用于this.props.children。

我也在使用next.js进行路由,难道是存在一种不同的方法来执行next的功能吗?

import React,{Component} from 'react';
import Header from './Header';
import { Container } from 'semantic-ui-react';
import Head from 'next/head';

class Layout extends Component {
    constructor(props){
        super(props);
        this.state = { user : props.user}
    }

    
    render(){
        const childrenWithProps = React.Children.map(this.props.children, child =>
            React.cloneElement(child, { userName: this.state.user })
          );
        return(
            <Container>
                <Head>
                    <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css" />
                </Head>
                <Header  />
                {childrenWithProps}
        </Container>
    )
    }


}

export default Layout;

React.cloneElement(...): The argument must be a React element, but you passed null.
Error: React.cloneElement(...): The argument must be a React element, but you passed null.
    at Object.cloneElement (http://localhost:3000/_next/1576310783506/main.js:4066:13)
    at Object.cloneElementWithValidation [as cloneElement] (http://localhost:3000/_next/1576310783506/main.js:5192:33)
    at http://localhost:3000/_next/1576310783506/page/accounts/uploadNew:179066:40
    at mapSingleChildIntoContext (http://localhost:3000/_next/1576310783506/main.js:4391:26)
    at traverseAllChildrenImpl (http://localhost:3000/_next/1576310783506/main.js:4253:5)
    at traverseAllChildrenImpl (http://localhost:3000/_next/1576310783506/main.js:4269:23)
    at traverseAllChildren (http://localhost:3000/_next/1576310783506/main.js:4334:10)
    at mapIntoWithKeyPrefixInternal (http://localhost:3000/_next/1576310783506/main.js:4416:3)
    at Object.mapChildren [as map] (http://localhost:3000/_next/1576310783506/main.js:4440:3)
    at Layout.render (http://localhost:3000/_next/1576310783506/page/accounts/uploadNew:179065:62)

1 个答案:

答案 0 :(得分:0)

我最终使用:this.props.children.slice(1)解决了这个问题,因为第一个元素在对象数组中未定义。