javascript - 如何从另一个组件的按钮运行组件的功能?
问题描述
这是组件TimeDisplay,我有函数handleTimer。
import React, {Component} from "react";
import format from './formatTime';
class TimeDisplay extends Component {
constructor(props) {
super(props);
this.state = {
time: 0,
on: false,
}
}
handleTimer = () => {
if (this.state.on) {
clearInterval(this.timer);
} else {
this.timer = setInterval(() => {
this.setState({time: ++this.state.time})
console.log("timer running");
}, 10)
}
this.setState({on: !this.state.on})
}
render() {
var time = format(this.state.time);
return <div>
<div className="controls">
<button onClick={this.handleTimer}>Run</button>
</div>
<h1 className="display-time">{time}</h1>
</div>
}
}
export default TimeDisplay;
现在,我想做的是创建一个按钮,其行为与 render() 中的按钮完全相同,但在另一个组件中。我该怎么做?
解决方案
如果您有两个组件,则将按钮保留在一个组件中并导入第二个组件并将handleTimer函数作为道具传递给下面的该组件,我正在举例
import React, {Component} from "react";
import format from './formatTime';
class ButtonAction extends Component {
constructor(props) {
super(props);
this.state = {
time: 0,
on: false,
}
}
handleTimer=()=>{
this.props.handleTimer();
}
render() {
var time = format(this.state.time);
return <div>
<div className="controls">
<button onClick={this.handleTimer}>Run</button>
</div>
<h1 className="display-time">{time}</h1>
</div>
}
}
export default ButtonAction ;
在 TimeDisplay 组件中导入 NewComponent
import NewComponent from "./ButtonAction ";
import React, {Component} from "react";
import format from './formatTime';
class TimeDisplay extends Component {
constructor(props) {
super(props);
this.state = {
time: 0,
on: false,
}
}
handleTimer = () => {
if (this.state.on) {
clearInterval(this.timer);
} else {
this.timer = setInterval(() => {
this.setState({time: ++this.state.time})
console.log("timer running");
}, 10)
}
this.setState({on: !this.state.on})
}
render() {
var time = format(this.state.time);
return <div>
<NewComponent handleTimer ={this.handleTimer} />
</div>
}
}
export default TimeDisplay;
推荐阅读
- firebase - 为什么 Cloud Firestore 集合至少需要一个文档?
- javascript - 在浏览器 JavaScript 中,将 csv 文本写入剪贴板时收到错误消息
- python - specutils fit_generic_continuum 在 Spectrum1D 上使用时给出 TypeError
- google-cloud-platform - 如何更改谷歌云 SQL 的时区?
- c# - System.CommandLine 异常处理
- java - Springfox 在 Swagger 2.0 JSON 定义中创建 'ref' 类型而不是 java.io.File 对象
- python - 类型错误:/:“list”和“int”不支持的操作数类型
- python - python,beautifulsoup 标签似乎没有类型
- ios - 为视图控制器视图的边界原点设置动画时实际会发生什么?
- css - 如何将我的 React 汉堡菜单齐平放在网站的右上角?