Enda Enda - 7 days ago 4
React JSX Question

How to call a method in the React component in an external script

I would like to call in the external script, or console React components of the method

I tried to do so

componentDidMount(){
window.mwap = this;
}


but no use

enter image description here

please help me

Answer

The return value of ReactDOM.render() is actually the mounted instance of the component:

class Counter extends React.Component {
  
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }
  
  inc() {
    this.setState({count: this.state.count + 1});
  }
  
  render() {
    return (
        <div>
          Count: {this.state.count}
        </div>
    )
  }
}

const instance = ReactDOM.render(
  <Counter />,
  document.getElementById('app')
);

instance.inc();
<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>

If you need access to a deeply nested component, that's a bit more difficult, but this should get you started.