eslint报错
[react/no-unstable-nested-components] Declare this component outside parent component “HelpModal” or memoize it. If you want to allow component creation in props, set allowAsProps option to true.
错误代码:
<ReactMarkdown
remarkPlugins={[gfm]}
components={{
// 在这里
code({ node, inline, className, children, ...props }) {
const match = /language-(\w+)/.exec(className || '');
return !inline && match ? (
<SyntaxHighlighter
children={String(children).replace(/\n$/, '')}
style={dark}
language={match[1]}
PreTag="div"
{...props}
/>
) : (
<code className={className} {...props}>
{children}
</code>
);
},
}}
>
{helpText}
</ReactMarkdown>
解决
参考:
How to fix ‘eslint-disable-next-line react/no-unstable-nested-components’
将代码抽离出来,并使用
useCallback
。
const renderCodeMarkdown = useCallback(({ node, inline, className, children, ...props }) => {
const match = /language-(\w+)/.exec(className || '');
return !inline && match ? (
<SyntaxHighlighter style={dark} language={match[1]} PreTag="div" {...props}>
{String(children).replace(/\n$/, '')}
</SyntaxHighlighter>
) : (
<code className={className} {...props}>
{children}
</code>
);
}, []);
<ReactMarkdown
remarkPlugins={[gfm]}
components={{
// 在这里
code: renderCodeMarkdown,
}}
>
{helpText}
</ReactMarkdown>
react-markdown
官方文档中,有指出components属性的用法,html标签
code
作为key,不同标签有不同的
props
。
另一个例子
在使用
antd Select
组件
的
dropdownRender
属性的时候,如果根据官方文档的写法也会存在eslint校验不通过的情况。
所以,同上处理方式,解决如下:
const renderDropdown = useCallback(
(menu) => {
return (
<>
{menu}
<Divider style={{ margin: '8px 0' }} />
<Space style={{ padding: '0 8px 4px' }}>
<Input
placeholder={`${t('shark-please-input')} ${t('shark-fe-case-create-start-page')}`}
ref={inputRef}
value={pagePathName}
onChange={(e) => setPagePathName(e.target.value)}
/>
<Button type="text" icon={<PlusOutlined />} onClick={addPagePathItem} disabled={!pagePathName}>
{t('shark-add')}
</Button>
</Space>
</>
);
},
[addPagePathItem, pagePathName, t],
);
<Select
style={{ width: 300 }}
placeholder={t('shark-fe-case-create-start-page') as string}
// 在这里
dropdownRender={renderDropdown}
options={pagePathOpts}
/>
版权声明:本文为weixin_43973415原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。