[英]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.