如何从另一个组件的按钮运行一个组件的功能?

时间:2019-05-04 13:19:58

标签: javascript reactjs

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

1 个答案:

答案 0 :(得分:0)

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