我是 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');
};
最佳答案
你不能直接使用另一个组件的内部函数,因为没有父子关系,我的建议是使用一些状态管理库来实现这种功能,例如 redux或mobx 它允许您通过组件属性分派(dispatch)函数并从应用程序状态检索一些数据。您可以查看this关于如何在现有 React 项目上实现 redux 的文章。
关于javascript - 如何访问reactjs中另一个组件的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59065850/