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

时间:2016-06-28 18:22:12

标签: javascript variables reactjs prop

我正在制作一个反应项目并使用wavesurfer.js。当我点击播放按钮时,我将道具播放从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;

3 个答案:

答案 0 :(得分:2)

您可以通过从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;

答案 1 :(得分:0)

你应该能够使用this.state访问状态变量。[变量]。在你的情况下this.state.playing和this.state.song

答案 2 :(得分:0)

React.js个组件中,state可以从内部访问所有当前this.state.<state name>值。