我只是在学习function &我只是不能让组件中的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>
);
}
}
发布于 2017-10-07 17:22:47
您需要绑定引用组件到函数的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();
}https://stackoverflow.com/questions/46622937
复制相似问题