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

标签 javascript reactjs

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

主要组件

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

最佳答案

你不能直接使用另一个组件的内部函数,因为没有父子关系,我的建议是使用一些状态管理库来实现这种功能,例如 reduxmobx 它允许您通过组件属性分派(dispatch)函数并从应用程序状态检索一些数据。您可以查看this关于如何在现有 React 项目上实现 redux 的文章。

关于javascript - 如何访问reactjs中另一个组件的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59065850/

相关文章:

javascript - 如何消除 ES6 导出语句中的 eslint 解析错误

javascript - 即使在使用 Object.assign 时,Redux 初始状态也会发生变化

javascript - 设置游标等待的最简单方法,然后让所有元素恢复原状

javascript - 单击按钮/JQuery 时使 div 彼此相邻

javascript - JavaScript 中的合并排序

javascript - 如何使用 React Native Video 显示外部字幕?

javascript - 如何显示当前的获取 url 以及我的状态发生了什么?

javascript - 内容协商 - 在 Firefox 中显示图像

javascript - Angular js在单独的文件中具有相同的$scope

javascript - 清除无状态 React 组件中的输入