【问题标题】:How do I get validator.js to work in react?如何让 validator.js 做出反应?
【发布时间】:2021-03-10 17:05:36
【问题描述】:

我对反应还很陌生。我有一个要求电子邮件验证的问题,我找到了一个名为 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 的东西时,这个块就起作用了。有什么遗漏吗?

【问题讨论】:

    标签: javascript reactjs wordpress-gutenberg gutenberg-blocks validator.js


    【解决方案1】:

    我认为这是因为contactInfo 没有在范围内定义。我认为应该是attributes.contactInfo。此外,您需要将const isValidEmail = validator.isEmail( contactInfo ); 移动到ContactEdit 中,只需将其放在return 语句之前即可。

    【讨论】:

    • 感谢您知道为什么底部的错误消息没有显示?
    • 我认为在您的情况下应该是{ !isValidEmail ? &lt;div className="error"&gt;invalid email&lt;/div&gt; : null },因为如果电子邮件无效,您需要显示错误
    猜你喜欢
    • 2021-05-12
    • 2021-05-13
    • 1970-01-01
    • 2020-12-07
    • 2021-08-10
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多