javascript - 无法访问 HOC 的类函数中的 Prop ,但能够在渲染中访问它们

标签 javascript reactjs react-native react-component

我要实现的目标: 我有很多表单,我想在我的 HOC 中保留表单验证逻辑,这样我就不必重复验证逻辑,因为大多数表单会有相同的字段和一些额外或更少的字段。

我是如何实现的:

学习创建 HOC,遵循这个例子 HOC example并尝试创建如下所示的 HOC。

import React from 'react';
import {
    spaceCheck,
    specialCharacterCheck,
    numberValidator
} from '../../utility/validators';

const fieldHOC = (WrappedComponent) => {
    class HOC extends React.Component {
            state = {
                error: {
                    name_first: {
                        fieldType: 'name_first',
                        errorType: 0
                    },
                    name_last: {
                        fieldType: 'name_last',
                        errorType: 0
                    },
                    email: {
                        fieldType: 'email',
                        errorType: 0
                    }
                }
            };

    getErrorMessage = (fieldType, errorType) => {
        this.setState({
            error: {
                ...this.state.error,
                [fieldType]: {
                    ...this.state.error[fieldType],
                    errorType
                }
            }
        });
    };

    checkFieldsError = (currentFocus, nextFocus) => {
       //Not able to get props passed by below component in class functions
        console.log('MY PROPS', this.props);
        const field = this.props[currentFocus];
        if (field === '' || spaceCheck(field)) {
            this.getErrorMessage(currentFocus, 1);
        } else if (specialCharacterCheck(field)) {
            this.getErrorMessage(currentFocus, 2);
        } else if (numberValidator(field) || numberValidator(field)) {
            this.getErrorMessage(currentFocus, 3);
        } else {
            this.setState({
                error: {
                    ...this.state.error,
                    [currentFocus]: {
                        ...this.state.error[currentFocus],
                        errorType: 0
                    }
                }
            });
        }
        this[nextFocus].focus();
    }
    render() {
        const { children } = this.props;
         // Here able to access props(name_first, name_last and email) passed from below component 
        // console.log('PROPS', this.props);
        return (
            <WrappedComponent
                {...this.props}
                error={this.state.error}
                checkFieldsError={this.checkFieldsError}
            >
                {children}
            </WrappedComponent>
        );
    }
    }
    return HOC;
};

export default fieldHOC;

我在其中使用此 HOC 的组件是

 const FieldValidation = fieldHOC(View);
    class Account extends Component {
        //Some class functions
      render() {
        const { spaceBottom, error } = this.state;
        return (
         <KeyboardAvoidingView
                        style={{ flex: 1 }}
                        keyboardShouldPersistTaps="handled"
                        behavior={Platform.OS === 'ios' ? 'padding' : null}
                    >
                        <KeyboardAwareScrollView
                            keyboardShouldPersistTaps="handled"
                            alwaysBounceVertical={false}
                            contentInset={{ bottom: 0 }}
                        >
                          <FieldValidation
                                name_first={this.state.name_first}
                                name_last={this.state.name_last}
                                email={this.state.email}
                                {...this.props}
                            >
                               <View
                                    style={[
                                        styles.UserContainer,
                                        CommonStyle.shadowStyle
                                    ]}
                                >
                                    <Text style={styles.headingTextStyle}>
                                        Account Details
                                    </Text>
                                    <FormTextInputComponent           
                                         {...testID('first_name')}
                                          errorType={this.props.error.name_first.errorType}
                                          onChangeText={this.handleTextChange('name_first')}
                                          textInputRef={ref => {this.name_first = ref;}}

                                          autoCapitalize="none"
                                          spellCheck={false}
                                          autoCorrect={false}
                                          blurOnSubmit={false}
                                          onSubmitEditing={() => {
                                                    this.props.checkFieldsError('name_first', 'name_last');
                                                }}
                                            />
                                        {this.props.error.name_first.errorType ?
                                                (
                                                    <ErrorMessage textColor="#EA2027" error={error.name_first} />
                                                )
                                                : null}
//Last part 
export default fieldHOC(connect(mapStateToProps)(Account));

在上面的组件中,我试图调用用 HOC 编写的验证函数,即 checkFieldsError . 我面临的问题是 Prop 传入 <FieldValidation喜欢name_first可以在 HOC 的渲染函数中访问,但在 HOC 的类函数中不能访问相同的 props。

很可能我尝试做的是 React 中的反模式(我的猜测)。有人可以帮我找出问题所在以及解决问题的正确方法吗?

编辑:codesandbox 中实现的示例 Example

最佳答案

这是一个codeSandBox example我已经创建了你想要实现的目标,你会注意到在 HOC 内部我尝试访问其功能中的 Prop ,还检查控制台以查看控制台日志,请检查代码并遵循相同的示例。您将获得相同的结果。

关于javascript - 无法访问 HOC 的类函数中的 Prop ,但能够在渲染中访问它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54713134/

相关文章:

javascript - 有没有办法关闭 Chrome 扩展程序或 Firefox 插件的源代码?

reactjs - Flow 会针对 React Native 中使用 bind() 的常见模式引发错误?

reactjs - react : is it true that react completes all updates within one cycle of reflow

javascript - 如何在 React Native 中渲染 BULLET 字符?

django - 与 Django Channels 的 React native Websocket 连接已打开,但没有消息通过

javascript - 如何使用 'this' 引用另一个标签内的图像?

php - 将参数从 php(mysql_query result) 传递到由 onchange 事件触发的 javascript 函数

javascript - 如果一个实体具有数组数据,如何在两个实体中建立关系

java - 使用 Selenium (Java) 与 React 下拉菜单交互 : "other element would receive the click"

react native 手势处理程序 :generateReleaseRFile FAILED trying to generate APK