Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

javascript - React.js Problem to sent props and event from parent to child

I start learning in React.js now. But I have some problem to sent props and event from parent to child In this workshop I want to click "Turn on All" and "Turn Off All" from parent and effect to child I can do this but in child have problem to set own state to turn on or off How can I set in child to do that ?

This is my code

App.js

import React,{useState} from 'react'
import './App.css'
import Lightbox from "./Lightbox"

function App() {

  const [OnOff, setOnOff] = useState(true)

  return (
    <div className="container">
      <div className="row mt-4 mb-4">
        <div className="col-md-12 text-center">
          <button onClick={()=>setOnOff(true)}>Turn On All</button> &nbsp;&nbsp;
          <button onClick={()=>setOnOff(false)}>Turn Off All</button>
        </div>
      </div>
      <div className="row">
        <Lightbox status={OnOff} />
        <Lightbox status={OnOff} />
        <Lightbox status={OnOff} />
        <Lightbox status={OnOff} />
        <Lightbox status={OnOff} />        
      </div>
    </div>
  );
}

export default App;

Lightbox.js

import React,{useState, useEffect } from 'react'

function Lightbox({status}) {

    const [data, setdata] = useState(true)
    const toggleHandler = () => setdata(!data)

    useEffect(() => {
        setdata(status)
    })

    return (
        
        <div className={`card col-md-2 m-2 p-3 ${data?'bg-warning':'bg-dark'}`}>
            {data?<div className="text-center mb-3 text-white">Light On</div>:<div className="text-center mb-3 text-white">Light Off</div>}
            <button onClick={toggleHandler}>{data?"OFF":"ON"}</button>
        </div>

    )
}

export default Lightbox

Thank for help

Screen shot

https://i.stack.imgur.com/wp5Xb.jpg

https://i.stack.imgur.com/DcMxL.jpg


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

try to mutate the state of children properly. Like this

const toggleHandler = () => setdata(data => !data )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...