[英]How to access method through ref React
I want to access a method from outside the component.我想从组件外部访问一个方法。 I found several tutorials that should allow me to call methods by
window.PathfindingVisualizer.resetGrid()
, but I'm getting an error saying resetGrid is not a function我找到了几个应该允许我通过
window.PathfindingVisualizer.resetGrid()
调用方法的教程,但是我收到一个错误,说 resetGrid 不是函数
example I tried to follow: https://brettdewoody.com/accessing-component-methods-and-state-from-outside-react/我尝试遵循的示例: https : //brettdewoody.com/accessing-component-methods-and-state-from-outside-react/
my App.js我的 App.js
function App() {
return (
<div className="App">
<PathfindingVisualizer
ref={(PathfindingVisualizer) => {window.PathfindingVisualizer = PathfindingVisualizer}}
/>
</div>
);
}
export default App;
my PathfindingVisualizer.js:我的 PathfindingVisualizer.js:
export default class PathfindingVisualizer extends React.Component {
constructor(props) {
super(props)
this.state = {
grid: [],
mouseLeftDown: false,
};
const mouseStrat = null;
}
resetGrid() {
//do stuff
}
componentDidMount() {
this.resetGrid();
this.mouseStrat = new MouseStrat(); //Object I want to call functions from
}
}
And I want to call the resetGrid()
and setState
from outside of react with:我想从外部调用
resetGrid()
和setState
与:
//errors resetGrid and setState is not a function
export class MouseStrat {
handleMouseDown(row, col) {
window.PathfindingVisualizer.resetGrid();
}
}
What am I doing wrong?我究竟做错了什么?
Where are you calling these functions?你在哪里调用这些函数? If they are being run too early
window.PathfindingVisualizer
may not have a value yet.如果它们运行得太早
window.PathfindingVisualizer
可能还没有值。 You may want to run them in a hook like componentDidUpdate
.您可能希望在像
componentDidUpdate
这样的钩子中运行它们。
So if I understand correctly, you have a component with a variable that is a class that contains a function that calls a function that's already in the component.因此,如果我理解正确的话,您有一个带有变量的组件,该变量是一个包含调用组件中已有函数的函数的类。 This seems quite complicated, and there may be a simpler solution to what you're trying to achieve.
这看起来很复杂,对于您要实现的目标,可能有一个更简单的解决方案。
Here's an alternative solution.这是一个替代解决方案。 Make
resetGrid
function a property of the MouseStrat class:使
resetGrid
函数成为 MouseStrat 类的一个属性:
export class MouseStrat {
constructor(resetGrid) {
this.resetGrid = resetGrid;
}
handleMouseDown(row, col) {
this.resetGrid();
}
}
Then, in PathfindingVisualizer
:然后,在
PathfindingVisualizer
:
export default class PathfindingVisualizer extends React.Component {
constructor(props) {
super(props)
this.state = {
grid: [],
mouseLeftDown: false,
mouseStrat: null // You had this as a variable before
};
this.resetGrid = this.resetGrid.bind(this); // You must bind your function for it to work properly in a React component
}
function resetGrid () {
//do stuff
}
componentDidMount() {
this.resetGrid();
this.mouseStrat = new MouseStrat(this.resetGrid); // Now you pass the function as an argument
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.