2017-10-23 6 views
1

を反応させて、私は1つの事について興味?は</p> <p>、私はこのようなアプリを持っている、と反応する通知システムを使用する通知システム

つまり、TestComponentで何かが起きたとき、App.jsの親コンポーネントを呼び出す方法は?

App.jsが君場合は、ルーティングシステム

xyz.com/test

<Route path='/test' component={TestComponent} /> 

App.js

export class App extends Component { 
(...) 
    <Navbar/> 
    <Footer /> 
    <TestComponent/> 

    <ToastNotif 
    ref="ToastNotifRef" 
    toastNotifStatus={this.state.toastNotifStatus}/> 

(...) 

ToastNotif.js

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

    componentDidMount(){ 
    this.notificationSystem = this.refs.notificationSystem; 
    } 

    componentWillReceiveProps(newProps) { 
    const {notificationList} = newProps; 
    console.log('componentWillReceiveProps', newProps); 
    const {removeNotification} = this.props; 

    if(newProps.toastNotifStatus==='deleted'){ 
     this.notificationSystem.addNotification({ 
      title: "xxx!", 
      message: 'xxx' 
      level: 'success', 
      autoDismiss: 0, 
      position: 'bl' 
     }); 
    }  
} 

render() { 
    console.log('toastnotifstatus (render)',this.state.toastNotifStatus) 
    return (
     <div className="notification-component-wrapper"> 
     <NotificationSystem ref="notificationSystem"/> 
     </div> 
    ) 

    } 

} 
export default ToastNotif; 

答えて

1

を持っていますアプリの状態をから更新したいあなただけのthis.props.onTestComponentChangeを呼び出して、新しい通知ステータスを渡す通知を表示する必要があるとき

export class App extends Component { 
updateToastNotification(newState){ 
    this.setState({ 
    toastNotifStatus: newState 
    }) 
} 

render(){ 
    return (
    (...) 
    <TestComponent onTestComponentChange={this.updateToastNotification.bind(this)}/> 
    <ToastNotif 
     ref="ToastNotifRef" 
     toastNotifStatus={this.state.toastNotifStatus}/> 
    (...) 
) 
} 

と内部<TestComponent>:あなたはそれに小道具としてコールバックを渡すことができます。

<ToastNotif>の外に通知システムを取得し、スタンドアロンコンポーネントにすることをお勧めします。

関連する問題