manuelBetancurt
manuelBetancurt

Reputation: 16128

react native call function from props constructor event listener

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

Upvotes: 0

Views: 1049

Answers (2)

Thakur Karthik
Thakur Karthik

Reputation: 3508

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>

Upvotes: 1

Nick Alves
Nick Alves

Reputation: 374

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

Upvotes: 1

Related Questions