我有一个应用程序,播放随机声音从选定的阵列根据您按下的按钮。我还想提供按需列出数组中所有声音的选项。
我一直在考虑使用.map循环和.map的各种不同的建议,但我总是遇到困难,因为我不能在对象上使用for循环。我认为。
class Randomizer extends React.Component {
constructor(props) {
super(props);
this.state = {
currentSound: {name: "laser", sound: "http://commondatastorage.googleapis.com/codeskulptor-assets/Collision8-Bit.ogg"},
myArray: [
{
name: 'laser',
sound: "http://commondatastorage.googleapis.com/codeskulptor-assets/Collision8-Bit.ogg"
},
{
name: 'laugh',
sound: "http://commondatastorage.googleapis.com/codeskulptor-assets/Evillaugh.ogg"
},
{
name: 'jump',
sound: "http://commondatastorage.googleapis.com/codeskulptor-assets/jump.ogg"
}
],
myArraySequel: [
{
name: 'laser2',
sound: "http://commondatastorage.googleapis.com/codeskulptor-assets/Collision8-Bit.ogg"
},
{
name: 'laugh2',
sound: "http://commondatastorage.googleapis.com/codeskulptor-assets/Evillaugh.ogg"
},
{
name: 'jump2',
sound: "http://commondatastorage.googleapis.com/codeskulptor-assets/jump.ogg"
}
]
}
}
newSound(arr){
this.setState((prevState)=>{
return {currentSound: prevState[arr][Math.floor(Math.random()*prevState[arr].length)]}
})
};
render() {
return (
<div>
<button onClick={()=>{this.newSound('myArray')}}>Sounds from myArray</button>
<button onClick={()=>{this.newSound('myArraySequel')}}>myArraySequel</button>
<div>
Listen!
<audio
autoPlay
src={this.state.currentSound.sound}>
</audio>
<h2>{this.state.currentSound.name}</h2>
</div>
<div>
<h2>sounds from myArray</h2>
{/* list of buttons with the name value as the the button name and it will play the sound associated when pressed */}
</div>
</div>
);
}
}
function App() {
return (
<div className="App">
<h1>RandomSoundboard</h1>
<Randomizer />
</div>
);
}
export default App;当我使用.map时,它告诉我当然要使用数组。
发布于 2019-10-21 11:22:08
你可以很容易地做到这一点,
语法应该是这样的,
array.map((element,index)=>(
<button>{element.name}</button>
))您的代码将如下所示
{
this.state.myArray.map((element,index)=>(
<button>{element.name}</button>
))
}https://stackoverflow.com/questions/58479282
复制相似问题