在渲染中更改状态参数是否反模式?

时间:2018-12-24 15:16:19

标签: reactjs

如果组件中的状态已更改,我需要制作简单的切换动画。但是我不想每次在React调用组件渲染时都显示此动画。我找到了一种方法,但是我不喜欢我需要直接更改状态变量而不使用setState并使其在render中。我也不喜欢每次在动画上生成新关键点的想法。我认为它是反模式的。如何以不同的方式获得相同的结果?

onClick() {
    if(this.props.items.length>=5) {
        this.setState({
            toggleWarning: true
        });

    }else {
        this.props.onStepAdd();
    }
}

render() {
    let toggle = "";
    let toggleKey = null;
    if(this.state.toggleWarning) {
        toggle = " "+style.toggleMsg;
        toggleKey = {key:Math.random()};
        this.state.toggleWarning = false;
    }

    return (
        <div>
            <h1>Add New</h1>
            <div>
                <Button
                    onClick={this.onClick}
                    label="Add Step"
                />
            </div>
            <div
                className={style.noteMsg + toggle}
                {...toggleKey} >
                <h3>Note: You can create only up to 5 steps for form wizard</h3>
            </div>
        </div>
    );
}

1 个答案:

答案 0 :(得分:1)

不确定我是否了解目标,但是如果您想单击一下添加一个类,然后在一段时间后删除该类:

previousTimeout = undefined
onClick = () => {
  if(this.props.items.length>=5) {
    this.setState({toggleWarning: true});
    clearTimeout(this.previousTimeout);
    this.previousTimeout = setTimeout(() => {
      this.setState({toggleWarning: false})
    }, 500);
}

render() {
  ...className={style.noteMsg + this.state.toggleWarning ? ' '+style.toggleMsg : ''}
}
相关问题