在我的渲染 return() 中,我有这些:
<button onClick={ this.selectTimeframe('Today') }
className={ this.setActiveIf('Today') } type="button">Today</button>
这是哪个函数:
selectTimeframe(timeframe) {
// this.setState({ timeframe });
}
^ 我现在必须注释掉 setState 否则我会收到我上面发布的错误并且应用程序会中断。
我的构造函数中有这个:
this.selectTimeframe = this.selectTimeframe.bind(this);
我在这里找到了这个答案,但这没有意义,我该如何传入变量?还是他说每个独特的按钮都需要独特的功能?至于避免在渲染内部调用它?
完整代码
import React from 'react';
export class TimeframeFilter extends React.Component {
constructor(props) {
super(props);
this.state = {
timeframe: 'Today'
};
this.selectTimeframe = this.selectTimeframe.bind(this);
this.setActiveIf = this.setActiveIf.bind(this);
}
componentDidMount() {
console.log('%c TimeframeFilter componentDidMount', 'background: #393939; color: #bada55', this.state);
}
selectTimeframe(timeframe) {
// this.setState({ timeframe });
}
setActiveIf(timeframe) {
return this.state.timeframe === timeframe ? 'btn btn-default active' : 'btn btn-default';
}
render() {
return (
<div className="fl">
<span className="label label-default mr10">Timeframe</span>
<div className="btn-group btn-group-sm mr20" role="group">
<button onClick={ this.selectTimeframe('Today') }
className={ this.setActiveIf('Today') } type="button">Today</button>
<button onClick={ this.selectTimeframe('Week') }
className={ this.setActiveIf('Week') } type="button">Week</button>
<button onClick={ this.selectTimeframe('Month') }
className={ this.setActiveIf('Month') } type="button">Month</button>
<button onClick={ this.selectTimeframe('Year') }
className={ this.setActiveIf('Year') } type="button">Year</button>
<button onClick={ this.selectTimeframe('All') }
className={ this.setActiveIf('All') } type="button">All</button>
</div>
</div>
);
}
}
export default TimeframeFilter;