0

I have some event listeners on my props

 constructor(props) {

    super(props);
    Tts.addEventListener("tts-start", event =>
        console.log("started"),
        this.setState({ ttsStatus: "started" })
        //how to call stopTTS
    ); ...}

so if I have a function outside the constructor

stopTTS() {
    console.log("cali");
}

how to call a function when the eventListener gets triggered? cheers

1
  • you can call simply with this.stopTTS..checkout my answer Commented Jun 20, 2020 at 6:08

2 Answers 2

1

First: If you can, use hooks instead.

A functional component that can do what you want could be:

import React, { useEffect, useState } from 'react'

const Component = () => {
  const [ttsStatus, setTtsStatus] = useState('')

  const stopTTS = () => {
    console.log("cali");
  }

  // This useEffect will work as a componentDidMount
  useEffect(() => {
    Tts.addEventListener("tts-start", event => {
      console.log("started"),
      setTtsStatus("started")
      stopTTS() // You can call stopTTS here
    })
  }, [])

  return null
}

export default Component

Try to avoid creating classes, the React Hooks were a new addition in React 16.8. They let you use state and other React features without writing a class, so you can have the power of a class in a cleaner function. You can know more about it in https://reactjs.org/docs/hooks-overview.html

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this comment made me understand modern functional stateless components
1

As i mentioned in the comment, you can call the class methods inside constructor like below snippet.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    }
    window.addEventListener('click', (e) => {
      if (this.state.count > 4) {
        this.alertCount();
      }
    });
  }
  alertCount = () => {
    alert('count has become 5')
    this.setState({
      count: 0
    })
  }
  clickHandler = () => {
    this.setState({
      count: this.state.count + 1
    })
  }
  render() {
    return ( 
    <div >
      <div> 
      The count is now {this.state.count} 
      </div> 
      <button onClick = {
        this.clickHandler
      } id = "btn" > Click Me < /button> 
      </div >
    );
  }
}

ReactDOM.render( < App / > , document.getElementById('root'))
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.