简体   繁体   English

如何重构有状态的React组件?

[英]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.

相关问题 如何在我的react组件中重构此ASYNC调用以使其更具可读性? - How can I refactor this ASYNC call in my react component to make it more readable? 我如何重构我的React组件以接受一系列错误并在error.show = true时显示其中任何错误的错误消息 - How can I refactor my React component to accept an array of errors and shows an error message if error.show = true for any one of those errors 我该如何重构呢? - how can I refactor this? 如何在我的组件上看到我的数组? / 反应 / Javascript - How can i see my array on my component ? / React / Javascript 如何从 React 组件中重构异步函数 - How to Refactor an Async Function out of a React Component 如何为渲染和逻辑重构反应组件? - How to refactor react component separate for rendering and logic? 如何重构 React 钩子以便我可以在回调中调用它? - How to refactor a React hook so that I can call it inside a callback? React Hooks - 我如何重构这些动态生成的输入? - React Hooks - How can I refactor these dynamically generated inputs? 如何将属性从有状态组件传递到包装子组件的 HOC 中使用的事件处理程序? - How can I pass attributes from a stateful component to an event handler used in an HOC wrapping a child component? 我如何在React.js中重构这些变量 - How can I refactor these variables in React.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM