gpt4 book ai didi

javascript - 在 ReactJS 中将类名添加到
onClick

转载 作者:行者123 更新时间:2023-11-30 14:42:43 25 4
gpt4 key购买 nike

我在 ReactJS 中构建了一个模式,需要通过单击 <a> 来触发它。添加.active模态类 <div className="newsletterModal"> .

一旦类作为 newsletterModal active 激活onClick={this.toggle.bind(this)}成功删除 active类,但如何添加 active我的 footer 中的类?

在 Newsletter.js 中

import React from 'react'
import PropTypes from 'prop-types';
import Link from 'gatsby-link';
class Newsletter extends React.Component {
constructor(props) {
super(props);
this.state = {addClass: false}
}
toggle() {
this.setState({addClass: !this.state.addClass});
}
render() {
let toggleModal = ["newsletterModal"];
if(this.state.addClass) {
toggleModal.push('active');
}
return(
<div className={toggleModal.join(' ')}>
<div className="newsletterContainer">
<span className="modalClose">
<a onClick={this.toggle.bind(this)} href="javascript:;"><svg>...</svg></a>
</span>
<content />
</div>
</div>
);
}
}
export default Newsletter

在 Footer.js 中(我希望链接添加在 Newsletter.js 中设置的类)

import React from 'react'
import PropTypes from 'prop-types';
import Link from 'gatsby-link'
const Footer = (props) => (
<footer>
<a onClick={this.toggle.bind(this)} href="javascript:;">
Newsletter
</a>
</footer>
)
export default Footer

index.js,其中两者都被调用到模板 - 请注意,我添加了一个类来显示此文件中的菜单。也许可以结合我的 is-menu-visiblenewsletterModal active

import React from 'react'
import PropTypes from 'prop-types';
import Helmet from 'react-helmet'
import { Link, withPrefix } from 'gatsby-link'
import '../assets/scss/main.scss'
import Header from '../components/global/Header'
import Menu from '../components/global/Menu'
import Newsletter from '../components/global/Newsletter'
import Footer from '../components/global/Footer'
class Template extends React.Component {
constructor(props) {
super(props)
this.state = {
isMenuVisible: false,
loading: 'is-loading'
}
this.handleToggleMenu = this.handleToggleMenu.bind(this)
}

componentDidMount () {
this.timeoutId = setTimeout(() => {
this.setState({loading: ''});
}, 100);
}

componentWillUnmount () {
if (this.timeoutId) {
clearTimeout(this.timeoutId);
}
}

handleToggleMenu() {
this.setState({
isMenuVisible: !this.state.isMenuVisible
})
}

render() {
const { children } = this.props

return (
<main id="app" className={`body ${this.state.loading} ${this.state.isMenuVisible ? 'is-menu-visible' : ''}`}>
<Helmet>
<link rel='shortcut icon' type='image/x-icon' href='/favicon.ico' />
</Helmet>
<div id="wrapper">
<div className="sub-wrapper">
<Header onToggleMenu={this.handleToggleMenu} />
<div className="gutter">
{children()}
<Footer />
</div>
</div>
</div>
<Menu/>
<Newsletter />
</main>
)
}
}

Template.propTypes = {
children: PropTypes.func
}

export default Template

最佳答案

关于javascript - 在 ReactJS 中将类名添加到 <div> onClick <a>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49418841/

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