问题
Suppose I have an App.js that puts two components on the screen. I now want to have one component (the MyButton) trigger function in the other component (MyCanvas) in this example. If MyCanvas would include MyButton, I probably could throw from MyButton something up into MyCanvas that changes a state there. But how do I do it if both components are on the same level? I basically want to have the structure like this, MyCanvas displays something while MyButton represents a component (or component-structure) that offers actions.
------
|App.js|
------
/ ^
v \
|Display | |Tool/Buttons|
|Component| |Component |
I can not call a method in MyCanvas from App.js as I understood it.
The ReactJS code generally has this structure:
Suppose this is the App.js
import React, {Component} from 'react';
import MyCanvas from './components/MyCanvas';
import MyButton from './components/MyButton';
class App extends Component {
changecanvas = () => {
//how can I pass something into Canvas component from here?
}
render(){
return (
<div className="App" >
<MyCanvas />
<MyButton />
</div>
);
}
}
And the Canvas component might be defined like this:
import React, {Component} from 'react';
import {canvas} from 'canvas';
class MyCanvas extends React.Component {
componentDidMount(){
// Make a New Canvas from a canvas package
this.the_canvas = new canvas('main-canvas', {
height: 100,
width: 100
});
}
//this supposed to be triggered on clicking MyButton
changeCanvasState = () => {
this.the_canvas.newState = true;
}
render(){
return (
<React.Fragment>
<canvas id="main-canvas"></canvas>
</React.Fragment>
);
}
}
And this supposedly defines a button that fires an action:
import React, {Component} from 'react';
import {Button} from 'react-bootstrap';
class MyButton extends React.Component {
changecanvas = () => {
//throw something up to App.js
}
render(){
return (
<React.Fragment>
<Button onClick={this.changecanvas}>Change state</Button>
</React.Fragment>
);
}
}
How do I get a state change triggered in MyCanvas.jsx by clicking MyButton component?
回答1:
App
should have some state that gets passed down to MyCanvas
.
App
should also pass down a callback function to MyButton
which updates that state. When MyButton
gets clicked, it should call that function. The updated state will automatically get propagated from App
to MyCanvas
because it is passed as a prop. You can read more in the official docs.
来源:https://stackoverflow.com/questions/58457819/how-do-i-trigger-a-state-change-in-a-component-on-reactjs