假设我有一个 App.js,它在屏幕上放置了两个组件。在此示例中,我现在希望在另一个组件 (MyCanvas) 中具有一个组件 (MyButton) 触发功能。如果 MyCanvas 包含 MyButton,我可能可以从 MyButton 中将某些内容扔到 MyCanvas 中,从而改变那里的状态。但是,如果两个组件都在同一级别,我该怎么做呢?我基本上想要这样的结构,MyCanvas 显示一些东西,而 MyButton 代表一个提供动作的组件(或组件结构)。
------
|App.js|
------
/ ^
v \
|Display | |Tool/Buttons|
|Component| |Component |
我不能按照我的理解从 App.js 调用 MyCanvas 中的方法。
ReactJS 代码一般是这样的结构:
假设这是 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>
);
}
}
Canvas 组件可以这样定义:
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>
);
}
}
这应该定义了一个触发动作的按钮:
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>
);
}
}
如何通过单击 MyButton 组件在 MyCanvas.jsx 中触发状态更改?