React ES6中的SetState

时间:2017-10-07 17:11:17

标签: reactjs es6-class

我刚学习React&我似乎无法在componentdidmount函数中使用setstate来工作。如果你可以帮助我,那将是可爱的。我已经尝试绑定它。

我不断收到错误,例如无法读取未定义的属性'setState'。

class ShareEvent extends React.Component {
	constructor(props) {
    super(props);
    this.state = {copied: false};

		this.componentDidMount = this.componentDidMount.bind(this);
  }

	componentDidMount() {
		var clipboard = new Clipboard('#copy-button');
        clipboard.on('success', function (e) {
          this.setState({copied: true});
          e.clearSelection();
        });
        clipboard.on('error', function (e) {
          document.getElementById("title").innerHTML = 'Please copy manually.';
        });
  }

	handleChange(event) {
		event.preventDefault();
		event.target.select();
  }

	render() {
		const EventURL = GenerateEventUrl(this.props.EventName,this.props.EventTimeUTC);
		return (
			<div>
        <h1>{this.state.copied ? "Copied!" : "Nicely done." }</h1>
        <p>Now, simply share the link below.<br />It will display{' '}
          <a href={EventURL}>the event</a>{' '}
          in the local time of whoever visits it.</p>
        <form>
          <div className="input-group">
            <input onClick={this.handleChange} type="text" className="form-control" defaultValue={EventURL} readOnly id="copy-input" />
            <span className="input-group-btn">
              <button className="btn btn-default" type="button" id="copy-button" data-clipboard-target="#copy-input" title="Copy to Clipboard">
                Copy
              </button>
            </span>
          </div>
        </form>
      </div>
		);
	}
}

1 个答案:

答案 0 :(得分:1)

您需要将引用组件的this绑定到您的函数。变化

function (e) {
    this.setState({copied: true});
    e.clearSelection();
}

function (e) {
    this.setState({copied: true});
    e.clearSelection();
}.bind(this)

或使用ES6箭头功能,自动绑定this

e => {
    this.setState({copied: true});
    e.clearSelection();
}