我尝试在componentDidMount
时使此功能起作用
但这没用。
componentDidMount = () => {
$('.button').click(function() {
var buttonId = $(this).attr('id');
$('#modal-container').removeAttr('class').addClass(buttonId);
$('body').addClass('modal-active');
});
$('#modal-container').click(function() {
$(this).addClass('out');
$('body').removeClass('modal-active');
});
console.log("hi");
}
答案 0 :(得分:1)
我假设您想更改元素的类别。您不需要使用componentDidMount()。所以我在下面加了一个例子。
class App extends React.Component {
constructor(props) {
super(props);
this.state = {addClass: false}
}
toggle() {
this.setState({addClass: !this.state.addClass});
}
render() {
let boxClass = ["box"];
if(this.state.addClass) {
boxClass.push('green');
}
return(
<div className={boxClass.join(' ')} onClick={this.toggle.bind(this)}>{this.state.addClass ? "Remove a class" : "Add a class (click the box)"}<br />Read the tutorial <a href="http://www.automationfuel.com" target="_blank">here</a>.</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
.box {
display: block;
width: 200px;
height: 200px;
background-color: gray;
color: white;
text-align: center;
vertical-align: middle;
cursor: pointer;
}
.box.green {
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
<div id="root">
</div>