gpt4 book ai didi

reactjs - 添加/删除类到父 DOM 元素 React js

转载 作者:行者123 更新时间:2023-12-03 13:34:15 25 4
gpt4 key购买 nike

我想在单击添加/删除按钮时从父 DOM 元素添加/删除类,就像我单击添加类按钮一样,它会将新的类名“clicked”添加到父 div 中,并在单击删除类时删除该类按钮:

index.html

<div class="main-div">

<div class="second-div" id="config">
</div>

</div>

config.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import Main from 'Main';

ReactDOM.render(
<Main/>,
document.getElementById('config')
);

Main.jsx

import ReactDOM from 'react-dom'
import React from "react";
import createReactClass from "create-react-class";


export default createReactClass({
getInitialState() {
return {
show-main-div: false
};
},

addClass() {
// want to add new class on parent DOM element i.e <div class="main-div">
},

render: function () {
return (
<div>
<button className="add-class" onClick={() => {this.addClass()}}>
Add Class
</button>
<button className="remove-class" onClick={() => {this.removeClass()}}>
Remove Class
</button>
</div>
);
}
});

最佳答案

分配引用并添加/删除所需的类:

addClass() {
this.divRef.current.classList.add('main-div')
},
removeClass() {
this.divRef.current.classList.remove('main-div')
}

render: function () {
return (
<div ref={this.divRef}>
<button className="add-class" onClick={() => {this.addClass()}}>
Add Class
</button>
<button className="remove-class" onClick={() => {this.removeClass()}}>
Remove Class
</button>
</div>
);
}

// note: you have to create a ref inside the constructor:
this.divRef = React.createRef()

关于reactjs - 添加/删除类到父 DOM 元素 React js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52364174/

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