gpt4 book ai didi

javascript - 如果我在 React 组件中创建一个变量,我如何在状态更改时重新访问它?

转载 作者:行者123 更新时间:2023-11-30 15:58:43 28 4
gpt4 key购买 nike

我正在制作一个 React 项目并使用 wavesurfer.js。当我按下播放按钮时,我将播放的 Prop 从 false 更改为 true,用于使元素实际播放的方法是 visual.playPause();但是,我不确定在创建变量后如何获取对变量的引用(该变量是在 initWaveSurfer 函数中创建的可视变量)。任何帮助都会很棒!!

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;

最佳答案

您可以通过从 this.initWavesurfer 返回它并从中设置您的状态来访问它。从那里,您可以通过 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;

关于javascript - 如果我在 React 组件中创建一个变量,我如何在状态更改时重新访问它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38083580/

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