I'm very new on React & JS so grateful on some tips :-) I have a grandfather stateful component App , a child stateless Drumpad who renders by a .map()
a, grandchild of App stateless Pad component. i'm trying to pass the onClick handler {handleClick}
as props from App to Pad, but seems not work. I'm stuck various days with this :-( here the code:
class App extends Component {
constructor(...props) {
super(...props);
this.state = {
power: false,
bank:"Smooth piano kit",
display: "Pulsa cualquier tecla",
volume: 30
};
this.handleClick = this.handleClick.bind(this)
}
handleClick(e, props) {
this.setState({
display: this.props.id
})
}
render() {
return (
<div className="App">
<Display display={this.state.display} />
<div className="Switches">
<Switch
name="power"
onSwitch={this.handleSwitchPower}/>
<Switch
name="bank"
onSwitch={this.handleSwitchBank}/>
</div>
<Slider2
value={this.state.volume}
onSlide={this.handleOnSlide} />
<Drumpad
bank={this.state.bank === "Heater kit"? sounds["Heater kit"]: sounds["Smooth piano kit"]}
handleClick={this.handleClick}
/>
</div>
);
}
}
export default App;
// child component Drumpad
import React from "react"
import Pad from '../components/Pad.jsx'
// import {sounds, MODE_NAMES} from '../data/sounds-constants.js'
const Drumpad = props => (
<div id='drum-machine'>
<div>{props.bank.map(d => (
<Pad
key={d.name}
id={d.name}
letter={d.shortcut}
src={d.link}
handleClick={props.handleClick}/>
))}
</div>
</div>
)
export default Drumpad
// grandchild component Pad
import React from "react"
import "../App.css"
const Pad = props => (
<div
className='drum-pad'
onClick={props.handleClick}
>
<h1 >{props.letter}</h1>
<audio id={props.letter}
className='clip'
src={props.src}>
</audio>
</div>
)
export default Pad
In your grandchild, call the function, instead of passing it as a reference:
<div
className='drum-pad'
onClick={() => props.handleClick(props.id)}>
Also, if you care about accessibility, attaching click handlers to a div is basically wrong, so either use a button, or give div a role="button"
attribute, while managing aria-pressed
state on your own. Simpler to use a button
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.