在 react-admin 中,如何为 UrlField href 添加前缀?

In react-admin, how can I prefix a UrlField href?

假设我有以下内容:

<UrlField source='fbUsername' />

如果结果是 fb 用户名 foo,则此链接相对于 /foo

(?) 如何将此 url 前缀为:

https://facebook.com/

所以结果是:

https://facebook.com/${fbUsername}

https://facebook.com/foo

<UrlField> 只接受 URL 值。对于您的用例,您应该编写一个基于 the UrlField source 的自定义字段。类似于:


import * as React from 'react';
import { Link } from '@material-ui/core';
import { useRecordContext } from 'react-admin';

const MyUrlField = ({ source }) => {
    const record = useRecordContext();
    const value = record && record[source];

    if (value == null) {
        return null;
    }

    return (
        <Link href={`https://facebook.com/${value}`}>
            {value}
        </Link>
    );
});

MyUrlField.defaultProps = {
    addLabel: true,
};

根据@françois-zaninotto 的回答,我修复了一个语法错误,修复了一些缺失的 useRecordContext() 参数,使它起作用:

// ###############################################
// FbUrlField.js
import * as React from 'react';
import { Link } from '@material-ui/core';
import { useRecordContext } from 'react-admin';

const FbUrlField = ( props ) =>
{
    const { source, target, rel } = props;
    const record = useRecordContext(props);
    const value = record && record[source];

    if (value == null) {
        return null;
    }

    return (
        <Link href={`https://facebook.com/${value}`} target={target} rel={rel}>
            {value}
        </Link>
    );
};

FbUrlField.defaultProps = {
    addLabel: true,
};

export default FbUrlField;


// ###############################################
// SomeList.js
import FbUrlField from './FbUrlField';
[...]
<FbUrlField
    label='FB'
    source='fbUsername'
    target='_blank' // New window
    rel="noopener noreferrer" // For security
/>