【问题标题】:Disable Button when clicked in React [duplicate]在 React 中单击时禁用按钮 [重复]
【发布时间】:2020-02-21 12:00:16
【问题描述】:

我制作了两个按钮组件,当我单击一个时,我想渲染另一个 onClick 以便能够禁用(因为它们看起来不一样)。

    const match = id;
    const checkId = this.state.pokemon.includes(match);

            {!checkId || this.state.isDisabled === true ? (
                        <button
                            onClick={() =>
                                this.setState({
                                    isDisabled: true
                                })
                            }
                        >
                            Get Pokemon
                        </button>
                    ) : (
                        <Button disabled/>
                    )}
                </div>

问题是按钮禁用仅在我刷新时才呈现,因为满足检查ID的条件但是我在单击后直接切换到禁用按钮时遇到问题

【问题讨论】:

  • button 还是Button?另外,是的,您应该在条件确定其disabled 值的位置移动一个按钮。编辑:沙盒:codesandbox.io/s/naughty-kowalevski-1iqis
  • 谢谢,它正在工作,但禁用所有按钮(我正在映射)以任何方式只停用一个??
  • 当然可以,但是显然每个按钮都需要一个单独的state 变量,即一个数组。

标签: javascript reactjs


【解决方案1】:

替换为

     <button disabled={!checkId || this.state.isDisabled}
                        onClick={() =>
                            this.setState({
                                isDisabled: true
                            })
                        }
                    />
                        Get Pokemon
       </button>

【讨论】:

    【解决方案2】:

    以下情况似乎有问题:

    {!checkId || this.state.isDisabled === true ? (

    我认为条件应该改为:

    !checkId || !this.state.isDisabled,因为据我所见,每当单击按钮时,isDisabled 状态都会设置为 true,它会将条件评估为真,因此永远不会执行虚假案例。

    如果你需要执行一次,根据match,你甚至可以将条件更改为:

    (!checkId &amp;&amp; !this.state.isDisabled)

    希望对你有帮助

    【讨论】:

    • 谢谢你的回答,但我还是一样,它只在我刷新页面时执行,而不是在我点击按钮时直接执行
    • 你能显示完整的代码吗??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 2020-03-11
    • 2012-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多