簡體   English   中英

從外部調用react組件

[英]Call react component from outside

是否可以從外部調用react組件? 例如

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");
  }
}

我必須從另一個組件調用Modal,但我不知道該如何實現。

嘗試調用更新類中state方法並獲取Warning: setState(...): Can only update a mounted or mounting component. 它需要打開模式(使用語義用戶界面)

使用狀態的方法

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'>

感謝幫助!

雖然不是最佳做法。 您必須在窗口中設置callReactModal函數

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

更好的方法是創建一個事件偵聽器,該事件偵聽器在觸發時打開模式。

不,不可能。 您所有的“自定義標簽”(反應組件)都應位於JSX內。 但是您可以根據需要在每個頁面上呈現多個React應用程序:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM