简体   繁体   中英

Pass Prop to Child component onClick

Depending on which link is clicked, I would like to update the img src in the MapImage Component

import React from 'react'
import NavLink from './NavLink'

var MapImage = React.createClass({
  render: function() {
    return <img src={'./img/' + this.props.img + '.png'} />
  }
});

export default React.createClass({
    getInitialState: function () {
    return { img: '1' }
  },

  loadImage: function () {
    this.setState({
        img: this.props.img
    });
  },  
  render() {
    return (
      <div>
        <h2>Maps</h2>
        <ul>
          <li><NavLink onClick={this.loadImage} to="/maps/firstfloor" img='1'>1st Floor</NavLink></li>
          <li><NavLink onClick={this.loadImage} to="/maps/secondfloor" img='2'>2nd Floor</NavLink></li>
          <li><NavLink onClick={this.loadImage} to="/maps/thirdfloor" img='3' >3rd Floor</NavLink></li>
        </ul>
        {this.props.children}
        <MapImage img={this.state.img} />
      </div>     
    )
  }
})

The image src is updated to ./img/undefined.png

You don't have that image value in the props when you're doing:

this.setState({
    img: this.props.img
});

Try to pass a parameter to the loadImage function, and use it in the setState :

// in JSX
onClick={ function () { this.loadImage(1); } }

// function
loadImage: function (img) {
    this.setState({
        img: img
    });
}

For each NavLink image.

In general, I'd recommend having an array and iterating over it, like:

var images = [{
   value: 'firstfloor',
   text: '1st Floor' 
}, 
{ ... // other objects }]

And then iterate like this (or change values depending on your logic):

{ 
   images.map((image, index) => {
      return (
         <li>
             <NavLink 
                   onClick={ function () { this.loadImage(index); } } 
                   to={ '/maps/' + image.value }
                   img={ index }>
                 { image.text }
             </NavLink>
         </li>
      );
   });
}

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