简体   繁体   中英

How to access the function of another component in reactjs?

I'm new to react and I'm facing a problem in the app I was trying to create. I have three components. So, in the main component, I fetch the data and send the data to the progressbar component, when the progressbar loads, I want to access the function of another component. how do I access the function of the other component?

Main Component

{analysis.tontop.map(({ tone, value }) => (
                    <MyProgressBar
                      onClick={() => this.handleSentClick(tone)} //this is where I want to call the function of the sound component. or is this not the correct place to call the function of the other component?
                      value={value}
                      text={tone}
                      key={tone}
                    />
                  ))}

Progressbar component

const MyProgressBar = ({ value, text, onClick }) => {
  return (
      <ProgressBar
        onClick={onClick}
        max={100}
        now={value}
      />
    </div>
  );
};

The component from where I want to access the function from

function Sound(tone, enteredText) { 

  const handleSentClick = ({ tone, onClick }) => { 
    //this is the function that I want to access in the main component
      console.log('something something');
    };

You can't use another components inner function directly since there is no parent - child relation, my suggestion is to use some state management library for that kind of functionality, like redux or mobx which lets you can dispatch functions and retrieve some data from application state via component props. You may check out this article for how to implement redux on existing react project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM