In html I create a audio button by this code
onClick
in react expects a function . But when you do onClick = {this.aud_play_pause()}
, it is returned a value . Change the onClick definition to
onClick = {this.aud_play_pause}
Code:
var React = require('react');
var Test = React.createClass( {
aud_play_pause() {
var myAudio = this.mytune;
if (myAudio.paused) {
myAudio.play();
} else {
myAudio.pause();
}
},
render () {
return(
<div>
<audio id="myTune" ref = {(ip)=> {this.mytune = ip}}>
<source src={require("./audio/rain.mp3")}/>
</audio>
<div className="col-md-2">
<div className="row">
<div className="col-md-12">
<a className="btn btn-block btn-lg btn-primary" data-toggle="button" onClick = {this.aud_play_pause}>Rain</a>
</div>
</div>
</div>
</div>
);
}
});
export default Test;
You will also need a bundler for instance webpack
to transpile your code.
See the setup example here:
Also if you use the latest version of React
, you will get a warning that afte v15.5.0
React.createClass
will be deprecated and hence it will be better to start of with the React.Component
import React from 'react';
class Test extends React.Component{
aud_play_pause() {
var myAudio = this.myTune;
if (myAudio.paused) {
myAudio.play();
} else {
myAudio.pause();
}
}
render () {
return(
<div>
<audio id="myTune" ref={(ip) => {this.mytune = ip}}>
<source src={require("./audio/rain.mp3")} />
</audio>
<div className="col-md-2">
<div className="row">
<div className="col-md-12">
<a className="btn btn-block btn-lg btn-primary" data-toggle="button" onClick = {this.aud_play_pause}>Rain</a>
</div>
</div>
</div>
</div>
);
}
}
export default Test;
Update your Test.js like below.
var React = require('react');
var Test = React.createClass( {
aud_play_pause: function() {
var myAudio = document.getElementById("myTune");
if (myAudio.paused) {
myAudio.play();
} else {
myAudio.pause();
}
},
render: function() {
return(
<div>
<audio id="myTune">
<source src="./audio/rain.mp3" />
</audio>
<div className="col-md-2">
<div className="row">
<div className="col-md-12">
<a className="btn btn-block btn-lg btn-primary" data-toggle="button" onClick = {this.aud_play_pause}>Rain</a>
</div>
</div>
</div>
</div>
);
}
});
export default Test;