在React中的onClick中的setInterval

时间:2016-02-02 22:44:46

标签: reactjs

更新:我对React(和js)很新,并且玩弄它。我想要做的是你每10秒钟只能点击一次图像。我该怎么做?我不知道在哪里重置isClickable。

我有这样的事情:

+--------------+--------------+------+-----+---------+-------+
| Field        | Type         | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| id           | varchar(15)  | NO   | PRI | NULL    |       |
| name         | varchar(150) | YES  |     | NULL    |       |
| first_price  | varchar(10)  | YES  | MUL | NULL    |       |
| second_price | varchar(10)  | YES  | MUL | NULL    |       |
+--------------+--------------+------+-----+---------+-------+

});

    Var ClickableImage = React.createClass({

getInitialState: function(){
    return {
        isClickable: false,
        counter: 0
    };
},

componentDidMount: function(){

    // componentDidMount is called by react when the component 
    // has been rendered on the page. We can set the interval here:
    setTimeout(() => {
        this.setState({
            isClickable: true,
        });
    }, 1000);

},

handleClick: function() {
    this.setState({ counter: this.state.counter+1 });

},

render: function(){

    var imgStyle = {
      width: '80%',
      height: '80%',
      backgroundColor: "#4ECDC4"
    };

    var counterStyle = {
      width: '80%',
      height: '80%',
      backgroundColor: "#674172"
    };

    const optionalOnClick = this.state.isClickable ? {
        onClick: this.handleClick,
        isClickable: false
    } : {};

    return(
            <div>
            <div style = {imgStyle}> 
                <img src={this.props.src} width="100%" height="80%" onClick={this.optionalOnClick}/>
            </div>
            <div style = {counterStyle}> 
                {this.state.counter} 
            </div>

            </div>
    )
}

1 个答案:

答案 0 :(得分:3)

我将如何做到这一点:

class ClickableImage extends Component {
    constructor(...args) {
        super(...args);

        this.state = {
            isClickable: false,
        };
    }

    componentDidMount() {
        setTimeout(() => {
            this.setState({
                ...this.state,
                isClickable: true,
            });
        }, 1000);
    }

    handleClick() {
        // ...
    }

    render() {
        const optionalOnClick = this.state.isClickable ? {
            onClick: this.handleClick,
        } : {};

        return (
            <img src={this.props.src} width="100%" height="80%" {...optionalOnClick} />
        );
    }
}

说明:

  1. 安装组件时 - 使用setTimeout将状态更改为isClickable: true
  2. 在渲染功能中检查是否设置了isClickable,如果是,则添加处理程序。