繁体   English   中英

无法将额外的道具传递给this.props.children

[英]Can't pass extra props to this.props.children

以下React组件处理通过this.props.children接收的我网站的通知的进入和退出动画:

class NotificationWrapper extends React.Component {

    constructor( props ) {              
        super( props );                 
        this.state = { timer: setTimeout( this.props.hideNotification, 3000 ) }     
    }

    static getDerivedStateFromProps( props, state ) {
        if( props.notification.override ) {             
            clearTimeout( state.timer );            
            return {
                timer: setTimeout( props.hideNotification, 3000 )            
            }       
        }       
        return null; 
    }

    handleCloseNotification() {         
        this.props.hideNotification();      
    }

    render() {      
        return(
            <CSSTransition 
                appear
                classNames="v-slide"            
                in={ this.props.in } 
                mountOnEnter
                timeout={ 200 }
                unmountOnExit
                onEntered={ () => { this.state.timer } }
            >
                { this.props.children }             
            </CSSTransition>
        );  
    }

}

function mapStateToProps( { notification } ) {  return { notification } }

export default connect( mapStateToProps, { hideNotification } )( NotificationWrapper );

通常它可以正常工作,但是我想将hideNotification道具传递给this.props.children这样,除了在三秒钟后自动隐藏之外,还可以通过单击包含在其中的“关闭”按钮来隐藏通知。子组件。

我已经阅读了React.cloneElement()并尝试将我的this.props.children替换为以下内容:

{
    React.cloneElement( this.props.children, {
        handleHideNotification: this.props.hideNotification
    })
}

但是当我对其进行测试时,将通知安装到DOM React就会立即引发以下错误:

标签上的prop handlehidenotification值无效。 从元素中删除它,或者传递一个字符串或数字值以将其保留在DOM中

我不明白问题是什么...

因为props.chidren就像一个组件列表,所以您必须对其进行迭代:

{React.Children.map(this.props.children, child => {
  return React.cloneElement(child, { handleHideNotification: 'your prop here' });
 })}

我认为解决问题的最佳方法是在关闭按钮中包含一个onClick事件,该事件会触发一种将调用props.hideNotification的方法。 您必须在注入props.children之前添加按钮。

 import React, { Fragment } from 'React'; class NotificationWrapper extends React.Component { constructor( props ) { super( props ); this.state = { timer: setTimeout( this.props.hideNotification, 3000 ) } } static getDerivedStateFromProps( props, state ) { if( props.notification.override ) { clearTimeout( state.timer ); return { timer: setTimeout( props.hideNotification, 3000 ) } } return null; } handleCloseNotification() { this.props.hideNotification(); } render() { return( <CSSTransition appear classNames="v-slide" in={ this.props.in } mountOnEnter timeout={ 200 } unmountOnExit onEntered={ () => { this.state.timer } } > <Fragment> <button onClick="handleCloseNotification">Close</button> { this.props.children } </Fragment> </CSSTransition> ); } } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM