0

我对反应还很陌生。我有一个要求电子邮件验证的问题,我找到了一个名为 validator.js 的 npm 包来处理这个问题。所以我构建了一个包含电子邮件地址的自定义 Gutenberg WordPress 块。我必须在验证器中调用的代码似乎使块停止渲染。这是代码:

import { __ } from '@wordpress/i18n';
import { SimpleText, TextFormats } from '../../components/SimpleText';
import validator from 'validator';

/**
 * @typedef {Object} ContactAttrs
 * @property {'full'} align
 * @property {string} contactName
 * @property {string} contactInfo
 */

/**
 * @param {import('@wordpress/blocks').BlockEditProps<ContactAttrs>} props
 */

const isValidEmail = validator.isEmail( contactInfo );

export function ContactEdit( { className, attributes, setAttributes } ) {
    return (
        <div className={ className }>
            <div className="block-align__wrapper">
                <SimpleText
                    identifier="contactName"
                    tagName="h5"
                    value={ attributes.contactName }
                    onChange={ ( contactName ) => setAttributes( { contactName } ) }
                    placeholder={ __( 'Enter contact name' ) }
                />
                <SimpleText
                    identifier="contactInfo"
                    tagname="a"
                    value={ attributes.contactInfo }
                    allowedFormats={ TextFormats.LINK }
                    onChange={ ( contactInfo ) => setAttributes( { contactInfo } ) }
                    placeholder={ __( 'Enter email address' ) }
                />
                { isValidEmail ? <div className="error">invalid email</div> : null }
            </div>
        </div>
    );
}

当我删除 validatoir.js 的东西时,该块起作用了。有什么遗漏吗?

4

1 回答 1

2

我认为这是因为contactInfo没有在范围内定义。我认为应该是attributes.contactInfo。你也需要搬进去,把它放在const isValidEmail = validator.isEmail( contactInfo );声明之前。ContactEditreturn

于 2021-03-10T17:17:17.873 回答