Reaction Executing a method inside a component

I have a component like this:

import React, { Component } from 'react';

class MyComponent extends Component {

  constructor(props, context) {
    super(props, context);
    this.state = {
      isActive: false,
    }
  }

  showMyComponent() {
    this.setState({
      isActive: true,
    });
  }

  hideMyComponent() {
    this.setState({
      isActive: false,
    });
  }

  render() {
    return (
      <div>
        <h1>Compoent Here</h1>
      </div>
    );
  }
}

export default MyComponent;

      

Now, in my index.js, I add a few components.

...

<Header />
<Nave />

      

Now I can do something like this:

MyComponent.showMyComponent();

      

How do you usually call a function?

If not, how to do it?

+3


source to share


3 answers


You can use links. In your method, render()

you can get the link. eg.

<MyComponent ref={ref => {this.myComponent = ref}}/>

      



You need to create a field myComponent

and assign it to it. With this, you can call it likethis.myComponent.showMyComponent()

See Refs and DOM here

+4


source


Use state

You think about how to react incorrectly. You won't need to call the components function like you ever did.

You can pass a prop to a component, which will cause the component to be hidden or shown.



or wrap the component in if

a parent. Use the parent state to hide or show the component.

how

if (someCondition) { <MyComponent /> }

+1


source


This can be done even if some people hate this option because this is not the official React way, true.

You can define any public method for your component classes (like reset method for Typeahead) and call those public methods using references (like this.refs.myTypeahead.reset ()). In most cases, making clearer use of React's inline dataflow instead of using refs is imperative.

But thinking out of the box is not forbidden, however, so you can use refs to do this.

class Parent extends Component {
  onSomeThing() {
    // Call some method of myChild
    this.myChild.myChildsPublicMethod()
  }

  render() {
    return <MyChild ref={ref => { this.myChild = ref; }} />
  }
}

// MyChild
// Just as demo using Pure components here.
// You could use the normal class notation.. 
const MyChild = () => <div>Ola</div>;
MyChild.someMethod = () => console.log('Ola');

      

More details here https://zhenyong.github.io/react/docs/more-about-refs.html

+1


source







All Articles