从组件外部访问React组件的方法/状态 [英] Access a React component method / state from outside the component

查看:61
本文介绍了从组件外部访问React组件的方法/状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过引用其ID来将 reactjs 组件嵌入到现有的HTML页面中,如React的教程中所述:

I have embedded a reactjs component into an existing HTML page by referencing it's ID like described in React's tutorial:

ReactDOM.render(
  <Page />,
  document.getElementById('my-react-compnent')
);

然后:

<div id="my-react-compnent></div>

组件将显示并按预期工作.

The component is displayed and works as expected.

现在,我想将位于该页面上的按钮链接到我的组件(具体来说,我想检索其状态,但是对于本示例,即使调用其方法之一也可以).

Now I want to link a button located on that page to my component (to be specific I would like to retrive its state, but for the example even invoking one of its methods would be fine).

换句话说-当单击外部按钮时,我要从 Page 组件调用方法吗?

In other words - when clicking the outside button, I want to invoke a method from the Page component?

我该怎么做?

推荐答案

旧建议

ReactDOM.render 分配返回的值确实允许访问组件及其方法.例如,在一个简单的应用程序中,我们可能有:

The Old Recommendation

Assigning the returned value from ReactDOM.render does allow access to the component and it's methods. For example, in a simple app, we might have:

const PageComponent = ReactDOM.render(<Page />, document.getElementById("app"));

然后我们可以使用 PageComponent 访问

,并且可以使用 PageComponent.METHOD 访问其任何方法.

which we can then access using PageComponent, and any of its methods can be accessed with PageComponent.METHOD.

但是 ,根据文档可能会更改或不建议使用,因此不建议这样做.

However, according to the docs this might be changed or deprecated and is not recommended.

新建议是将回调 ref 附加到根元素.使用上面的相同示例:

The new recommendation is to attach a callback ref to the root element. Using the same example above:

const PageComponent = ReactDOM.render(<Page ref={(pageComponent) => {window.pageComponent = pageComponent}}/>, document.getElementById("app"));

然后可以使用 window.pageComponent 访问

,并且可以使用 window.pageComponent.METHOD 访问其任何方法.

which we can then access using window.pageComponent, and any of its methods can be accessed with window.pageComponent.METHOD.

这也适用于子组件.

这是一个完整的示例:

class ChildComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0
    }
  }

  returnCounter = () => {
    return this.state.counter;
  }
  
  increment = (event) => {
    event.stopPropagation();
    this.setState(prevState => {
      return {
        counter: prevState.counter + 1
      }
    })
  }
  
  render() {
    return (
      <div onClick={this.increment}>
        Child Value - {this.state.counter} - Click to increment
      </div>
    )
  }
}

class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0
    }
  }

  returnCounter = () => {
    return this.state.counter;
  }
  
  increment = () => {
    this.setState(prevState => {
      return {
        counter: prevState.counter + 1
      }
    })
  }

  render() {
    return (
      <div onClick={this.increment}>
        <div>Parent Value - {this.state.counter} - Click to increment</div>
        <ChildComponent ref={(childComponent) => {window.childComponent = childComponent}}/>
      </div>
    )
  }
}

ReactDOM.render(<Page ref={(pageComponent) => {window.pageComponent = pageComponent}} />, document.getElementById("app"));

const parentBtn = document.getElementById("parentButton");
parentBtn.addEventListener("click", event => {
  alert(window.pageComponent.returnCounter());
});

const childBtn = document.getElementById("childButton");
childBtn.addEventListener("click", event => {
  alert(window.childComponent.returnCounter());
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>

<button id="parentButton">Get Parent State</button>
<button id="childButton">Get Child State</button>

这篇关于从组件外部访问React组件的方法/状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆