这里是 JS 新手,正在从事 React 项目,我本质上希望将按钮的可见性属性设置为 false,以便在选中复选框时更改为 true,这是我的代码,我相信逻辑就在那里,但对于某些人来说原因没有反映在用户界面上,任何建议表示赞赏
const [visible, setVisibility] = useState(false)
function clicked() {
console.log('in cliked')
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('in the visible for loop')
continueButton.setAttribute('visibility', 'visible')
}
}
上面的代码是我在返回 JSX 之前定义的代码,然后在 JSX 中我调用这段代码如下...
<input type='checkbox' id='acknowledged' onClick={clicked}></input>
因此,本质上,当单击此复选框时,使用 onClick 属性,我传递了之前传递的单击函数,该函数具有一个带有回调函数的事件监听器,用于更改按钮的可见性
在回答你的问题之前,我想指出你的函数中有很多经典的 JavaScript 逻辑,这些逻辑应该通过钩子使用,而不是直接使用。 React 使用虚拟 DOM,而 Vanilla JS 使用真实 DOM,两者之间存在一些显着差异。
document.getElementById();
getAttribute();
setAttribute();
你可以通过官方的 React 教程来掌握如何在 React 中做事,这与传统的 Javascript 有点不同。
解决问题的正确方法应该如下:
import "./styles.css";
import { useState } from "react";
export default function App() {
// 1. the variable 'visible' 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) => !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 (
<div className="App">
<label>
Checkbox
{/* 2. The input checkbox has a onClick Handler function passed as reference, meaning that function will be called when the checkbox is clicked. */}
<input type="checkbox" onClick={onClickHandle} />
</label>
{/* 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 'checked', else return 'not checked' */}
<h2>Check box is {visible ? "checked" : "not checked"}</h2>
</div>
);
}