gpt4 book ai didi

javascript - 如何将 prop 传递给事件处理程序?

转载 作者:行者123 更新时间:2023-11-28 12:17:56 24 4
gpt4 key购买 nike

我有 4 个 spanonClick={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>
);
}
}

关于javascript - 如何将 prop 传递给事件处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44909156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com