【问题标题】:ReactJS - button onClick gets called during renderReactJS - 在渲染期间调用按钮 onClick
【发布时间】:2017-05-16 16:33:30
【问题描述】:

我有一个带有type="range" 的表格。现在我想添加 3 个按钮来更改与表单相同的值。出于某种原因,按钮 onClick 事件似乎在调用渲染函数时被重复调用。

这是我的组件:

class Slider extends Component {
    constructor(props) {
        super(props);

        this.handleChange = this.handleChange.bind(this);
        this.handleButton = this.handleButton.bind(this);
    }

    handleChange() {
        this.props.onSetCountdown(parseInt(this.refs.seconds.value, 10));
    }

    handleButton(value) {
        this.props.onSetCountdown(parseInt(value, 10));
    }

    render() {
        return(
            <div>
                <form className={styles.ttSlider} ref="form">
                    <input max="480" min="60" name="slider" onChange={this.handleChange} ref="seconds" type="range" value={this.props.totalSeconds}/>
                    <button onClick={this.handleButton(60)}>1min</button>
                    <button onClick={this.handleButton(180)}>3min</button>
                    <button onClick={this.handleButton(300)}>5min</button>
                </form>
            </div>
        )
    }
}

Slider.propTypes = {
    totalSeconds: React.PropTypes.number.isRequired,
    onSetCountdown: React.PropTypes.func.isRequired
};

这是来自父组件:

handleSetCountdown(seconds) {
        this.setState({
            count: seconds
        });
    }

从父组件渲染:

<Slider totalSeconds={count} onSetCountdown={this.handleSetCountdown}/>

这是我得到的错误:

警告:setState(...):在现有状态期间无法更新 过渡(例如在render 或其他组件的 构造函数)。渲染方法应该是 props 的纯函数和 状态;构造函数副作用是一种反模式,但可以移动 到componentWillMount

对我来说,这看起来像是在组件仍在渲染时调用了 onClick 按钮。我做错了什么?

【问题讨论】:

标签: javascript reactjs ecmascript-6


【解决方案1】:

这是因为不是将函数传递给事件 onClick,而是直接调用该函数。

尝试这样做:

<button onClick={() => { this.handleButton(60)}}>1min</button>
<button onClick={() => { this.handleButton(180)}}>3min</button>
<button onClick={() => { this.handleButton(300)}}>5min</button>

在这里找到答案:React onClick function fires on render

希望对你有帮助!

【讨论】:

    【解决方案2】:

    如果你出于某种原因不想使用匿名函数,第二种方法是直接在渲染函数处使用绑定。然后你可以在你的构造函数中删除行:)

    <button onClick={this.handleButton.bind(this, 60)}>1min</button>
    

    【讨论】:

    • 我一直在研究这个问题,因为我遇到了与 OP 相同的问题,并且在其他类似线程上,人们建议绑定 this in the constructor 而不是在渲染方法中绑定。
    猜你喜欢
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    相关资源
    最近更新 更多