gpt4 book ai didi

reactjs - 在 React JS 中添加和删除一个类列表

转载 作者:行者123 更新时间:2023-12-02 16:23:41 24 4
gpt4 key购买 nike

我在 react js 中使用功能组件,在下面的代码中类 right-panel-active 没有被添加/未定义。有人帮助启用在切换按钮时添加类

import React from 'react';
import './style.css';
import {
Modal,
DropdownMenu
} from '../MaterialUI';

/**
* @author
* @function Header
**/

const Header = (props) => {

const container = () => {
document.getElementById('container');
}
const signUpButton = () => {
container.classList.add('right-panel-active');
};
const signInButton = () => {
container.classList.remove('right-panel-active');
};

return (
<div className="header">
<div className="container" id="container">
<button className="ghost" id="signIn" onClick={signInButton} >Sign In</button>
</div>
<div className="overlay-panel overlay-right">
<p>Enter your personal details and start journey with us</p>
<button className="ghost" id="signUp" onClick={signUpButton} >Sign Up</button>
</div>
</div>
)

}

export default Header

最佳答案

您没有使用 React 的任何功能。

Read about state management in ReactEvent Handlers in React

const Header = (props) => {
const [isContainerActive, setIsContainerActive] = React.useState(false);
const signUpButton = () => {
setIsContainerActive(false);
};
const signInButton = () => {
setIsContainerActive(true);
};

return (
<div className="header">
<div id="container" className={`container${isContainerActive ? " right-panel-active" : ""}`}>
<button className="ghost" id="signIn" onClick={signInButton}>Sign In</button>
</div>
<div className="overlay-panel overlay-right">
<p>Enter your personal details and start journey with us</p>
<button className="ghost" id="signUp" onClick={signUpButton}>Sign Up</button>
</div>
</div>
);
}

ReactDOM.render(<Header />, document.getElementById("root"));
.header {height: 120px;}
.container {float:left;}
.overlay-right {display: none;background: red;float:right;height:100%;}
.right-panel-active ~ .overlay-right {display: inline-block;}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>

PS:我也推荐https://www.npmjs.com/package/classnames ,或用于类名管理的 cx 库。

关于reactjs - 在 React JS 中添加和删除一个类列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65010686/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com