如何使用JavaScript根据复选框的状态改变按钮的可见性?

huangapple go评论152阅读模式
英文:

How to get button to change visibility based on checkbox in JavaScript

问题

我是你的中文翻译助手,以下是翻译好的内容:

    const [visible, setVisibility] = useState(false)

    function clicked() {
        console.log('在 clicked 函数中')
        const check = document.getElementById('acknowledged')
        check.addEventListener('click', showContinueButton())
        setVisibility(true)
    }


    function showContinueButton() {
        
        const continueButton = document.getElementById('continue')

        console.log(continueButton.getAttribute("visibility"))
        if(visible) {
            console.log('在可见的循环中')
            continueButton.setAttribute('visibility', 'visible')
        }
        
    }

上面的代码是我在返回 JSX 之前定义的代码,然后在 JSX 中按如下方式调用这段代码...

<input type='checkbox' id='acknowledged' onClick={clicked}></input>

所以当点击这个复选框时,使用 onClick 属性,我传递了之前传递的点击函数,该函数具有一个带有回调函数的事件监听器,用于改变按钮的可见性。

英文:

new to JS here and working on a react project, I want to essentially have the button's visibility attribute which is set to false to change to true when a checkbox is checked, here is my code and I believe the logic is there but for some reason is not reflected on the UI, any advice is appreciated

    const [visible, setVisibility] = useState(false)

    function clicked() {
        console.log(&#39;in cliked&#39;)
        const check = document.getElementById(&#39;acknowledged&#39;)
        check.addEventListener(&#39;click&#39;, showContinueButton())
        setVisibility(true)
    }


    function showContinueButton() {
        
        const continueButton = document.getElementById(&#39;continue&#39;)

        console.log(continueButton.getAttribute(&quot;visibility&quot;))
        if(visible) {
            console.log(&#39;in the visible for loop&#39;)
            continueButton.setAttribute(&#39;visibility&#39;, &#39;visible&#39;)
        }
        
    }

the code above is the code I have defined before the return JSX, then within the JSX I call this code as followed...

&lt;input type=&#39;checkbox&#39; id=&#39;acknowledged&#39; onClick={clicked}&gt;&lt;/input&gt;

So essentially when this checkbox is clicked, using the onClick attribute, I pass the click function I passed earlier which has an eventListener with a callback function to change the visibility of the button

答案1

得分: 3

使用状态(state),您无需操作CSS。

以下是一个示例供您参考:

const [visible, setVisibility] = useState(false);
let clicked = e => {
  setVisibility(e.target.checked);
}
return (
  <div>
    &nbsp; <input type="checkbox" onClick={clicked}/> 
    {
      visible &&
      <button> Button1 </button>
    } 
  </div>
)
英文:

With the use of a state, you don't need to manipulate the CSS.

Here is an example for your reference:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const [visible, setVisibility] = useState(false);
let clicked = e =&gt; {
  setVisibility(e.target.checked);
}
return ( 
  &lt;div&gt;
     &amp;nbsp; &lt;input type = &quot;checkbox&quot; onClick = {clicked}/&gt; 
     {
      visible &amp;&amp;
      &lt;button&gt; Button1 &lt;/button&gt;
     } 
  &lt;/div&gt;
)

<!-- end snippet -->

答案2

得分: 1

另一种变体是 @The KNVB 已经说过的:

const [visible, setVisible] = useState(false);

return (
    <div>
        <input type="checkbox" onClick={() => setVisible(!visible)}/>
        <br />
        { visible && <button>可见按钮</button> } 
    </div>
)
英文:

Another variation of what @The KNVB already said:

const [visible, setVisible] = useState(false);

return (
    &lt;div&gt;
        &lt;input type=&quot;checkbox&quot; onClick={() =&gt; setVisible(!visible)}/&gt;
        &lt;br /&gt;
        { visible &amp;&amp; &lt;button&gt;visible button&lt;/button&gt; } 
    &lt;/div&gt;
)

答案3

得分: 0

我想指出,在你的函数中有很多经典的JavaScript逻辑,应该通过hooks来使用,而不是直接使用。

因此,这些原始函数在React中有更好的替代方案。

document.getElementById();
getAttribute();
setAttribute();

解决你的问题的正确方法应该是这样的:

import { useState } from "react";

export default function App() {
  // 1. 变量 'visible' 的初始值为 false
  const [visible, setVisible] = useState(false);

  /*
  3. 点击按钮的处理函数更新状态(变量 visible 的值)为与当前值相反的值,
  如果为 true,则变为 false,如果为 false,则变为 true
   */
  function onClickHandle() {
    setVisible((visible) => !visible);
  }
  /*
  5. 逻辑
  每当应用程序的状态发生变化时,该函数都会被返回,也就是说每当用户点击复选框时,变量 visible 的状态都会发生变化,从而重新渲染组件。
  */
  return (
    <div className="App">
      <label>
        复选框
        {/* 2. 输入复选框具有传递引用的 onClick 处理函数,意味着当复选框被点击时,该函数将被调用。 */}
        <input type="checkbox" onClick={onClickHandle} />
      </label>
      {/* 4. 应用程序 - 处理逻辑的示例,我使用了三元运算符,但基本上它的意思是,如果 visible 的值为 true,则返回 'checked',否则返回 'not checked' */}
      <h2>复选框 {visible ? "已选中" : "未选中"}</h2>
    </div>
  );
}

这里有一个可工作的示例

英文:

I want to point out that there are a lot of classical JavaScript logic in your functions, which should be used via hooks, and not directly.

Hence these vanilla functions have better alternatives in React.

document.getElementById();
getAttribute();
setAttribute();

The right way to resolve your issue should instead be as follows:

import { useState } from &quot;react&quot;;

export default function App() {
  // 1. the variable &#39;visible&#39; has initial value equal to false
  const [visible, setVisible] = useState(false);

  /*
  3. The click handle button updates the state (variable value of visible) to opposite of whatever it is,
  if true , then false, if false, then true
   */
  function onClickHandle() {
    setVisible((visible) =&gt; !visible);
  }
  /*
  5. LOGIC
  This function is returned everytime the state of the application changes, meaning everytime a user clicks on the checkbox, the state of var visible changes, and hence the component rerenders.
  */
  return (
    &lt;div className=&quot;App&quot;&gt;
      &lt;label&gt;
        Checkbox
        {/* 2. The input checkbox has a onClick Handler function passed as reference, meaning that function will be called when the checkbox is clicked. */}
        &lt;input type=&quot;checkbox&quot; onClick={onClickHandle} /&gt;
      &lt;/label&gt;
      {/* 4. Application - An example of how to handle the logic, I have used terinary operator but basically it is saying if the value of visible if visible, return &#39;checked&#39;, else return &#39;not checked&#39; */}
      &lt;h2&gt;Check box is {visible ? &quot;checked&quot; : &quot;not checked&quot;}&lt;/h2&gt;
    &lt;/div&gt;
  );
}

Working example here

答案4

得分: 0

const [visible, setVisibility] = useState(false)

<button
style={{visibility:visible?'visible':'hidden'}}
>
继续
</button>

<input
type='checkbox'
onClick={()=>{setVisibility(previousVisibility => !previousVisibility)}}
/>

英文:
const [visible, setVisibility] = useState(false)

&lt;button 
  style={{visibility:visible?&#39;visible&#39;:&#39;hidden&#39;}}
&gt;
  continue
&lt;/button&gt;

&lt;input
  type=&#39;checkbox&#39; 
  onClick = {()=&gt;{setVisibility(previousVisibility =&gt; !previousVisibility)} 
/&gt;

huangapple
  • 本文由 发表于 2023年8月9日 08:55:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76863944.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定