提问者:小点点

如何用div id呈现多个div背景颜色变化


当点击div背景颜色时将变为蓝色再次点击div颜色将变为白色。。。使用动态id.。。请帮助我如何在reactjs中做

$(document).ready(function($){
    $('#my_checkbox').on('change',function(){
      if($(this).is(':checked')){
        $("#card").css('background-color',"blue");
      }else{
        $("#card").css('background-color','white');
      }
    })
  }) 

jqury代码


共2个答案

匿名用户

null

$(document).ready(function($){
    $('#my_checkbox').on('change',function(){
      if($(this).is(':checked')){
        $("#card").css('background-color',"blue");
      }else{
        $("#card").css('background-color','white');
      }
    })
  }) 
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id ="card" style="height:300px;width:200px;">
 <input type="checkbox" id="my_checkbox" />
</div>
</body>
</html>

匿名用户

在react中,您只需以两种方式使用组件状态

功能组件

import React, { useState } from 'react'

function SomePage() {
  const [toggle, setToggle] = useState(false)

  return (
    <div>
      <button onClick={() => setToggle(!toggle)}>Click Me</button>
      <div style={{ color: toggle ? 'red' : 'blue' }}>my color is changed</div>
    </div>
  )
}

类组件

import React from 'react'

class SomePage extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      toggle: false
    }
  }

  render() {
    return (
      <div>
        <button onClick={() => this.setState({ toggle: !toggle })}>Click Me</button>
        <div style={{ color: this.state.toggle ? 'red' : 'blue' }}>my color is changed</div>
      </div>
    )
  }
}

这是react的基本级别,您应该根据您的需要进行调整