首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SetState in React ES6

SetState in React ES6
EN

Stack Overflow用户
提问于 2017-10-07 17:11:16
回答 1查看 837关注 0票数 1

我只是在学习function &我只是不能让组件中的setstate工作。如果你能帮我的话那就太可爱了。我已经试过把它绑起来了。

我一直收到一些错误,比如无法读取未定义的属性“setState”。

代码语言:javascript
复制
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>
		);
	}
}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-07 17:22:47

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

代码语言:javascript
复制
function (e) {
    this.setState({copied: true});
    e.clearSelection();
}

代码语言:javascript
复制
function (e) {
    this.setState({copied: true});
    e.clearSelection();
}.bind(this)

或者使用ES6箭头函数,它自动绑定this

代码语言:javascript
复制
e => {
    this.setState({copied: true});
    e.clearSelection();
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46622937

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档