class PlayerControls extends React.Component {
constructor(props) {
super(props)
this.state = {
loopActive: false,
shuffleActive: false,
}
}
render() {
var shuffleClassName = this.state.toggleActive ? "player-control-icon active" : "player-control-icon"
return (
<div className="player-controls">
<FontAwesome
className="player-control-icon"
name='refresh'
onClick={this.onToggleLoop}
spin={this.state.loopActive}
/>
<FontAwesome
className={shuffleClassName}
name='random'
onClick={this.onToggleShuffle}
/>
</div>
);
}
onToggleLoop(event) {
// "this is undefined??" <--- here
this.setState({loopActive: !this.state.loopActive})
this.props.onToggleLoop()
}
Run Code Online (Sandbox Code Playgroud)
我想loopActive在切换时更新状态,但是this在处理程序中未定义对象.根据教程文档,我this应该参考该组件.我错过了什么吗?
我正在尝试将<canvas>我在这里找到的这个很酷的动画转换为React可重用组件.看起来这个组件需要一个父组件用于画布,并且需要许多子组件function Ball().
出于性能原因,制作Balls无状态组件可能会更好,因为它们会有很多.我对制作无状态组件并不熟悉,并且想知道我应该在哪里定义this.update()和定义的this.draw函数function Ball().
无状态组件的功能是在组件内部还是外部?换句话说,以下哪项更好?
1:
const Ball = (props) => {
const update = () => {
...
}
const draw = () => {
...
}
return (
...
);
}
Run Code Online (Sandbox Code Playgroud)
2:
function update() {
...
}
function draw() {
...
}
const Ball = (props) => {
return (
...
);
}
Run Code Online (Sandbox Code Playgroud)
各自的优点/缺点是什么,并且对于像我这样的特定用例更好?