简体   繁体   中英

How can I map elements which Ive got from database?

I want to ask you how can I map elements from database. I basically want to make something like: (name = {name}, isOn = {isOn}) . 在此处输入图片说明

And the code of the component which should get assigned data:

const Islbutton = props => {
  const [name, setName] = useState('');
  const [isOn, setIsOn] = useState(true);
  // some functions
  return (
    <div>
      <img src = {isOn ? islon : isloff} alt= "" onClick={() =>toggleImage()}/>
    </div>
  );
}

You need to use useEffect to handle external property change in a function component. See the example below,

 const { Component, useState, useEffect } = React; const { render } = ReactDOM; const Islbutton = props => { const { toggleLight } = props; const [name, setName] = useState(''); const [isOn, setIsOn] = useState(false); useEffect(() => { setName(props.naem); setIsOn(props.isOn); }); const islon = "https://cdg-webhosting.com/wp-content/uploads/2011/02/help-hint-icon.png"; const isloff = "https://i.ya-webdesign.com/images/light-bulb-on-off-png-16.vnd"; // some functions return ( <img src={isOn ? islon : isloff} alt={name} onClick={toggleLight} /> ); }; class App extends Component { state = { lights: [ { name: "light1", isOn: true }, { name: "light2", isOn: false }, { name: "light3", isOn: false }, { name: "light4", isOn: true }, { name: "light5", isOn: true } ] }; constructor(props) { super(props); } toggleLight = light => { return () => { this.setState(prevState => ({ lights: prevState.lights.map(_light => { return _light === light ? { ...light, isOn: !light.isOn } : _light; }) })); }; }; render() { const { lights } = this.state; return ( <div> {lights.map(light => ( <Islbutton key={light.name} name={light.name} isOn={light.isOn} toggleLight={this.toggleLight(light)} /> ))} </div> ); } } render(<App />, document.querySelector("#root"));
 img { width: 50px; height: auto; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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