首页 > 解决方案 > reactjs中如何访问另一个组件的功能?

问题描述

我是新手,我在尝试创建的应用程序中遇到问题。我有三个组件。因此,在主组件中,我获取数据并将数据发送到进度条组件,当进度条加载时,我想访问另一个组件的功能。如何访问其他组件的功能?

主要部件

{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}
                    />
                  ))}

进度条组件

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

我要从中访问功能的组件

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');
    };

标签: javascriptreactjs

解决方案


你不能直接使用另一个组件内部函数,因为没有父子关系,我的建议是使用一些状态管理库来实现这种功能,比如reduxmobx ,它可以让你调度函数并从应用程序中检索一些数据通过组件道具状态。你可以查看这篇文章,了解如何在现有的 react 项目上实现 redux。


推荐阅读