2017-02-16 38 views
2

可以從外部調用反應組件嗎? 例如來自外部的呼叫反應組件

HTML

<div id='react-app'></div> 

<button onClick=callReactModal()>PressME</button> 

我的分量,我想調用方法

let callReactModal = function() { 
    console.log('clicked'); 
    //Navigation.sayHello(); 
} 

class Navigation extends React.Component<any, any> { 

    constructor(props:any){ 
    super(props); 

    this.state = { 
     language: { 
     lang: cookie.load('lang') || '' 
     } 
    }; 
    this.click = this.click.bind(this); 
    } 

    sayHello =() => { 
    alert("Hello"); 
    } 
} 

我不得不從另一個組件調用模態,但我不知道如何實現那。

試圖調用方法,更新state類和獲取Warning: setState(...): Can only update a mounted or mounting component.它需要開放模式(使用語義UI),它採用了先進

handleOpen = (e) => this.setState({ 
     modalOpen: true, 
    }) 

modalPart

方法

<Modal size='small' open={this.state.modalOpen} onClose={this.handleClose} trigger={<a className="btn btn-base" onClick={this.handleOpen}>Login</a>} closeIcon='close'> 

感謝幫幫我!

+0

你需要定義sayHello'靜態',但問題是爲什麼? – juancab

+0

告訴我'未捕獲的ReferenceError:callReactModal沒有被定義' –

+0

看在這[[fiddle](https://jsfiddle.net/odzck2a3/) – juancab

回答

3

雖然不是最佳實踐。你必須設置callReactModal功能窗口

window.callReactModal = function() { 
    console.log('clicked'); 
    //Navigation.sayHello(); 
} 

來實現它更好的方法,是創建一個觸發時打開模態事件偵聽器。

+0

這是正確的,但像Hoyen說的,你可能不應該這樣做。如果可能,最好將所有內容都放在反應組件內。 – ShaneDaugherty

+0

或創建一個組件與模態 – juancab

+0

認爲這是不好的做法 但它是這樣使用它的基本要求 謝謝你們! –

0

不,這是不可能的。所有的「自定義標籤」(React組件)都應該位於您的JSX內部。但是,如果你願意,你可以在每頁上渲染多個React應用程序:

<div id='react-app'></div>  
<div id='react-button'></div> 
+0

有可能,可以通過附加到窗口或在裏面編碼標籤與瀏覽器中的babel transpiler,雖然不是一種好的做法 – juancab

+0

知己:) –