[英]How can I refactor my stateful React component?
I have a stateful Key
component that represents a Key in a Keyboard like so: 我有一个有状态的
Key
组件,它表示键盘中的键,如下所示:
import React from 'react';
class Key extends React.Component {
constructor(props) {
super(props);
this.state = {
id: props.id,
customClass: props.customClass,
value: props.value,
onAction: props.onAction,
active: false
};
this.handleAction = this.handleAction.bind(this);
this.resetActiveState = this.resetActiveState.bind(this);
}
handleAction(e) {
e.preventDefault();
this.setState ({
active: true
});
this.state.onAction(this.state.value);
//remove key pressed effect after 150 ms by resetting active state
_.delay(() => this.resetActiveState() , 150);
}
resetActiveState() {
this.setState ({
active: false
});
}
render() {
//conditionalProps is empty when active is false.
let conditionalProps = {};
let className = `default-btn ${this.state.customClass}`;
let displayValue = this.state.value;
//enable css attribute selector
if (this.state.active){
conditionalProps['data-active'] = '';
}
return (
<button id={this.state.id} key={this.state.id} className={className}
data-value={this.state.value} {...conditionalProps} onTouchStart={this.handleAction}>
{displayValue}
</button>
);
}
}
Key.defaultProps = {
customClass: '',
onAction: (val) => {}
};
export default Key;
onTouchStart
is used to detect a touch event. onTouchStart
用于检测触摸事件。
onTouchStart
handler changes active
state to true
. onTouchStart
处理程序将active
状态更改为true
。
Component
re-renders with the appropriate css to give key clicked effect. Component
使用适当的CSS重新渲染以提供按键效果。
After 150ms, active
state is set to false using resetActiveState()
. 150ms之后,使用
resetActiveState()
将active
状态设置为false。
Component re-renders without the key clicked effect css. 组件重新渲染,而没有单击效果css。
conditionalProps
attribute is used to conditionally add css styles (using css attribute selector) to achieve 'key pressed' look in the rendered component. conditionalProps
属性用于有条件地添加css样式(使用css属性选择器),以在呈现的组件中实现“按键”外观。
This works as expected but I was wondering if it would be possible to refactor the component so I can extract the logic to maybe a parent component which I can then extend using the Key component. 这可以按预期工作,但是我想知道是否可以重构该组件,以便可以将逻辑提取到父组件,然后可以使用Key组件进行扩展。
This would be a perfect use case for a Higher Order Component . 对于高阶组件来说,这将是一个完美的用例。
This will allow you to abstract much of the functionality and pass it down to stateless components as props. 这将允许您抽象出许多功能,并将其作为道具传递给无状态组件。
The React official docs do a great job of explaining how to use HOCs. React官方文档在解释如何使用HOC方面做得很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.