如何访问reactjs中另一个组件的功能?

时间:2019-11-27 08:19:03

标签: javascript 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');
    };

1 个答案:

答案 0 :(得分:0)

您不能直接使用其他组件内部函数,因为没有父子关系,我的建议是使用某种状态管理库来实现这种功能,例如reduxmobx 它使您可以调度功能并通过组件属性从应用程序状态检索一些数据。您可以查看this文章,了解如何在现有的React项目上实现redux。