我无法弄清楚如何执行以下代码。本质上,我希望在它的父元素的上下文中对子元素进行求值,以便引用指向父元素。我希望我的伪代码有意义。
<Comment>
<UndoButton timeout="120">
// "this" context would point to UndoButton
Your comment will post in {this.state.timeLeft} {this.state.timeUnit}.
</UndoButton>
</Comment>
<Note>
<UndoButton timeout="60">
Undo your note for {this.state.timeLeft} more {this.state.timeUnit}.
</UndoButton>
</Note>
----------------------------
UndoButton = react.createClass
getInitialState: function() {
return {timeLeft: this.props.timeout, timeUnit: 'seconds'};
},
componentDidMount: function() {
this.timer = setInterval(function(){
var timeUnit;
var timeLeft = this.state.timeLeft - 1;
if (timeLeft === 0) {
clearInterval(this.timer);
}
else {
newState = {timeLeft: timeLeft};
if (timeLeft === 1) {
newState.timeUnit = 'second';
}
this.setState(newState);
}
}, 1000);
},
render: function() {
<div>
{this.props.children} // THIS IS WHERE THE MESSAGE WOULD GO
<button>undo</button>
</div>
}