首页 > 解决方案 > 如何从另一个组件的按钮运行组件的功能?

问题描述

这是组件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() 中的按钮完全相同,但在另一个组件中。我该怎么做?

标签: javascriptreactjs

解决方案


如果您有两个组件,则将按钮保留在一个组件中并导入第二个组件并将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;

推荐阅读