来自外部的呼叫反应组件

时间:2017-02-16 18:47:29

标签: javascript reactjs

可以从外面调用反应组件吗? 例如

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.的方法需要打开模态(使用semantic-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'>

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

虽然不是最好的做法。你必须在窗口中设置callReactModal函数

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

实现它的更好方法是创建一个事件监听器,在触发时打开模态。

答案 1 :(得分:0)

不,这是不可能的。所有“自定义标记”(React Components)都应该在JSX中。但是,如果需要,您可以在每页上呈现多个React应用程序:

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