React ES6中的SetState
问题描述:
我刚刚学习React &我似乎无法在componentdidmount函数中使setstate工作。如果你能帮助我,这将是可爱的。我已经试图绑定它。React ES6中的SetState
我不断收到错误,如无法读取未定义的属性'setState'。
class ShareEvent extends React.Component {
\t constructor(props) {
super(props);
this.state = {copied: false};
\t \t this.componentDidMount = this.componentDidMount.bind(this);
}
\t componentDidMount() {
\t \t 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.';
});
}
\t handleChange(event) {
\t \t event.preventDefault();
\t \t event.target.select();
}
\t render() {
\t \t const EventURL = GenerateEventUrl(this.props.EventName,this.props.EventTimeUTC);
\t \t return (
\t \t \t <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>
\t \t);
\t }
}
答
您需要绑定您的组件引用到你的功能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();
}
真棒!谢谢。