我有4个span
和onClick={this.clickhandler}
。在clickhandler
内,有一个音频,我想单击该音频即可播放。问题是,我希望在同一clickhandler
中包含4个不同的音频URL。如何将每个span
与音频字符串相关联并将其传递给相同的eventhandler
?
clickhander(e) {
const audio = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound1.mp3');
audio.play()
console.dir(e.target)
}
render() {
return(
<div className="container">
<h1 className="header">Simon Game</h1>
<span onClick={this.clickhander}>
<Heart fill="#555"/>
</span>
<span onClick={this.clickhander}>
<Heart fill="#402" />
</span>
<span onClick={this.clickhander}>
<Heart fill="#f39" />
</span>
<span onClick={this.clickhander}>
<Heart fill="#29f" />
</span>
</div>
)
}
编辑:我尝试下面的解决方案,但我收到此错误:您提供的错误不包含堆栈跟踪。
现在这是我的代码:
class Home extends Component {
constructor(props){
super(props)
}
clickhander(e, url) {
const str = url
const audio = new Audio(String(str));
audio.play()
}
render() {
return(
<div className="container">
<h1 className="header">Simon Game</h1>
<span onClick={this.clickhander.bind(this, "https://s3.amazonaws.com/freecodecamp/simonSound1.mp3")}>
<Heart fill="#555"/>
</span>
<span onClick={this.clickhander}>
<Heart fill="#402" />
</span>
<span onClick={this.clickhander}>
<Heart fill="#f39" />
</span>
<span onClick={this.clickhander}>
<Heart fill="#29f" />
</span>
</div>
)
}
}
export default Home
最佳答案
在React中,尝试考虑类似组件。app.js
class App extends Component {
audioArr = ['link1', 'link2', 'link3']; // links to songs
render() {
return (
<div className="App">
{this.audioArr.map((link, i) => (
<Player link={link} key={i} />
))}
</div>
)
}
}
Player.js
class Player extends Component {
handleClick = () => {
const audio = new Audio(this.props.link);
audio.play();
};
render() {
return (
<div>
<span onClick={this.handleClick}>
<Heart fill="#29f" />
</span>
</div>
);
}
}