我想写个组件,自动加数字,然后点击【计数】按钮后取消自动加数字,改成每点击一次加1

Ba.Component.jsx

import React from 'react';

import ClockButton from './Ba.Button.jsx';


const element =(enumber) => (
    <div>
        <ClockButton Clear={a}/>
        <h1>自己写的定时组件</h1>
        <h2>我的时间是{enumber}</h2>
    </div>
);

class Clock extends React.Component {
    constructor(props) {
        super(props);
        this.state = {number: 0};
    }

    tick() {

        const nextNumber = this.state.number + 1

        this.setState({ number: nextNumber });

    }

    componentDidMount() {
        let a = setInterval(this.tick, 3000);
    }

    render() {
        return (
            element(this.state.number)
        );
    }
}
export default Clock;

Ba.Button.jsx

import React from 'react';

class ClockButton extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <button>计数</button>
        );
    }
}
export default ClockButton;
阅读 4.3k
1 个回答

先说说你代码的问题,Ba.Button.jsx这个里面作为子组件,你需要绑定事件,可是你连onClick事件都没有,其次:Ba.Component.jsx这个父组件,你封了一个独立的element函数,可是没有写在组件的内部,写在组件外部也行,但是你需要把组件内部的一些state和方法作为参数传递过来,方便传递到对应的子组件上,可以改的方式很多,不该你的结构的话主要的修改点:

  1. setInterval句柄是需要处理的,你放在didmount里面,但是且没有保存到组件里,你下次怎么清楚这个定时器?所以需要保存定时器句柄
  2. 其次子组件需要有事件处理,需要向父组件传递,所以可以在父组件中编写方法,传递给子组件,子组件通过props来绑定方法,
    Ba.Button.jsx修改:
class ClockButton extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <button onClick={this.props.clear}>计数</button>
        );
    }
}

Ba.Component.jsx修改:

const element =(enumber, stopAdd) => (
    <div>
        <ClockButton clear={stopAdd} />
        <h1>自己写的定时组件</h1>
        <h2>我的时间是{enumber}</h2>
    </div>
);

class Clock extends React.Component {
    constructor(props) {
        super(props);
        this.state = {number: 0};
    }

    tick() {

        let nextNumber = this.state.number + 1;

        this.setState({ number: nextNumber });

    }

    componentDidMount() {
        this.a = setInterval(()=> this.tick(), 1000);
    }
    stopAdd(){
      this.a && clearInterval(this.a) && delete this.a;
      this.tick();
    }
    render() {
        return element(this.state.number, this.stopAdd.bind(this));
    }
}

ReactDOM.render(<Clock name="John" />, document.getElementById('root'));

测试页面:https://codepen.io/gaearon/pe...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题