【问题标题】:Not able to pass additional props to {this.props.children}无法将其他道具传递给 {this.props.children}
【发布时间】:2020-04-07 13:08:41
【问题描述】:

我是 React 的新手,想在我的布局组件(它是父组件)中将某个参数作为道具传递给 {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)

【问题讨论】:

  • 您是否尝试过在传递给 React.cloneElement 之前过滤子项? React.Children.filter(child =&gt; child !== null).map( ... )
  • 是的,我已经尝试过了,但是它给出了一个错误,“_react2.default.Children.filter 不是一个函数”...

标签: reactjs jsx next.js


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-01-07
    • 2017-11-19
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 2014-11-19
    相关资源
    最近更新 更多