[英]If I make a variable inside a react component, how do I re-access it on a state change?
I am making a react project and using wavesurfer.js. 我正在做一个反应项目,并使用waveurfer.js。 When I hit a play button I change the prop playing from false to true, the method used to make the element actually play is visual.playPause();
当我按下播放按钮时,我将道具的播放从假更改为真,用于使元素实际播放的方法是visual.playPause();。 however, I'm not sure how I would get a reference back to the variable after I created it (the variable being visual which was created inside the initWaveSurfer function).
但是,我不确定在创建变量后如何获取对变量的引用(变量是在initWaveSurfer函数内部创建的可视变量)。 Any help would be amazing!!
任何帮助都将是惊人的!
var React = require('react');
var ReactDom = require('react-dom');
var reactWaveSurfer = React.createClass({
getInitialState: function(){
return ({
song: this.props.song,
playing: this.props.playing
});
},
componentDidMount: function () {
this.initWavesurfer();
},
componentWillReceiveProps: function(nextProps) {
this.setState({
playing: nextProps.playing
});
},
initWavesurfer: function () {
var visualContainer = ReactDom.findDOMNode(this.refs.waveContainer);
var visual = WaveSurfer.create({
container: visualContainer,
waveColor: 'blue',
progressColor: 'purple',
barWidth: '3',
height: "90",
maxCanvasWidth: 200
});
visual.load(this.state.song.audio_url);
},
render: function () {
return <div className="wave-surfer" ref="waveContainer" ></div>;
}
});
module.exports = reactWaveSurfer;
You can access it by returning it from this.initWavesurfer
and setting your state from that. 您可以通过从
this.initWavesurfer
返回它并this.initWavesurfer
设置状态来访问它。 From there, you can access it thru this.state.visual
; 从那里,您可以通过
this.state.visual
;访问它。
var React = require('react');
var ReactDom = require('react-dom');
var reactWaveSurfer = React.createClass({
getInitialState: function(){
return ({
song: this.props.song,
playing: this.props.playing
});
},
componentDidMount: function () {
this.setState({visual: this.initWavesurfer()}); //You now have access to visual thru this.state.visual
},
componentWillReceiveProps: function(nextProps) {
this.setState({
playing: nextProps.playing
});
},
initWavesurfer: function () {
var visualContainer = ReactDom.findDOMNode(this.refs.waveContainer);
var visual = WaveSurfer.create({
container: visualContainer,
waveColor: 'blue',
progressColor: 'purple',
barWidth: '3',
height: "90",
maxCanvasWidth: 200
});
visual.load(this.state.song.audio_url);
return visual;
},
render: function () {
return <div className="wave-surfer" ref="waveContainer" ></div>;
}
});
module.exports = reactWaveSurfer;
you should be able to access state variable using this.state.[variable]. 您应该可以使用this.state。[variable]访问状态变量。 In your case this.state.playing and this.state.song
在您的情况下,this.state.playing和this.state.song
在React.js
组件中,可以通过this.state.<state name>
从自身内部访问所有当前state
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.