[英]Use a string key name with React PropTypes
我需要使用字符串作为我作为对象传递给一些React组件的对象的键。 有没有办法使它与React PropTypes一起使用并传递eslint?
这是一些示例代码:
MyComponent.propTypes = {
'string-key-name': PropTypes.shape({
foo: PropTypes.func.isRequired,
bar: PropTypes.string.isRequired,
}).isRequired,
};
在上面的代码中, string-key-name
引起了问题。 我需要使用-
在此对象的键名中。 这可能吗?
编辑
我尝试在字符串键周围放置方括号,例如['string-key-name']
,但它不起作用。
编辑2
我收到的eslint错误是缺少道具验证错误。 奇怪的是, 'string-key-name'
并不缺少,但是foo
和bar
都没有。
'.foo' is missing in props validation react/prop-types
'.bar' is missing in props validation react/prop-types
编辑 :由于缺乏信息,这是一个完全不相关的答案。
如果要使用方括号,则应放置变量而不是字符串文字。
const keyName = 'string-key-name';
MyComponent.propTypes = {
[keyName]: PropTypes.shape({
foo: PropTypes.func.isRequired,
bar: PropTypes.string.isRequired,
}).isRequired,
};
不过,我认为你可以禁用eslint在这种情况下,因为你要使用-
反正。
'string-key-name': PropTypes.shape({ // eslint-disable-line
要么
// eslint-disable-next-line
'string-key-name': PropTypes.shape({
会成功的
我终于弄明白了。
在MyComponent
我像这样破坏了道具:
render() {
const { foo, bar } = this.props['string-key-name'];
return (
<div>
{bar}
</div>
);
当我如下修改代码时,道具验证问题消失了。
render() {
const props = this.props;
return (
<div>
{props['string-key-name'].bar}
</div>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.