简体   繁体   English

如何使用 div id 渲染多个 div 背景颜色变化

[英]How to render multiple div background color change with div id

While onclick the div background color will change to blue again click the div color will change to white.. with dynamic id... please help how can I do in reactjs虽然 onclick div 背景颜色将再次变为蓝色,单击 div 颜色将变为白色.. 使用动态 id ......请帮助我在 reactjs 中该怎么做

jQuery code: jQuery 代码:

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

 $(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>

In react you simply use the component state in 2 ways在反应中,您只需以两种方式使用组件 state

Function Component Function 组件

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>
  )
}

Class Component Class 组件

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>
    )
  }
}

this is the basic level of react, you should adjust to your needs这是反应的基本水平,您应该根据自己的需要进行调整

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM