我想要以编程方式反应原生的字符串格式的打印类名称。任何人都可以告诉我,我该怎么做?
答案 0 :(得分:17)
在JavaScript中,您可以使用class Demo extends React.Component {
componentDidMount(){
console.log(this.constructor.name); // "Demo"
}
}
获取课程名称。
instance.type.displayName
对于JSX组件,您可以使用let text = <Text></Text>;
console.log(text.type.displayName) // "Text"
。例如:
{{1}}
答案 1 :(得分:0)
如果您查看/Libraries/Renderer/implementations/ReactNativeRenderer-prod.js
,会发现内部代码定义了用于获取组件名称的函数。我已经将其带出并更新为RN:
const REACT_PORTAL_TYPE = Symbol.for('react.portal'),
REACT_FRAGMENT_TYPE = Symbol.for('react.fragment'),
REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode'),
REACT_PROFILER_TYPE = Symbol.for('react.profiler'),
REACT_PROVIDER_TYPE = Symbol.for('react.provider'),
REACT_CONTEXT_TYPE = Symbol.for('react.context'),
REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref'),
REACT_SUSPENSE_TYPE = Symbol.for('react.suspense'),
REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list'),
REACT_MEMO_TYPE = Symbol.for('react.memo'),
REACT_LAZY_TYPE = Symbol.for('react.lazy'),
REACT_BLOCK_TYPE = Symbol.for('react.block');
export const getComponentName = (type) => {
if (null == type) return null;
if ('function' === typeof type) return type.displayName || type.name || null;
if ('string' === typeof type) return type;
switch (type) {
case REACT_FRAGMENT_TYPE:
return 'Fragment';
case REACT_PORTAL_TYPE:
return 'Portal';
case REACT_PROFILER_TYPE:
return 'Profiler';
case REACT_STRICT_MODE_TYPE:
return 'StrictMode';
case REACT_SUSPENSE_TYPE:
return 'Suspense';
case REACT_SUSPENSE_LIST_TYPE:
return 'SuspenseList';
}
if ('object' === typeof type)
switch (type.$$typeof) {
case REACT_CONTEXT_TYPE:
return (type.displayName || 'Context') + '.Consumer';
case REACT_PROVIDER_TYPE:
return (type._context.displayName || 'Context') + '.Provider';
case REACT_FORWARD_REF_TYPE:
var innerType = type.render;
innerType = innerType.displayName || innerType.name || '';
return type.displayName || ('' !== innerType ? 'ForwardRef(' + innerType + ')' : 'ForwardRef');
case REACT_MEMO_TYPE:
return getComponentName(type.type);
case REACT_BLOCK_TYPE:
return getComponentName(type.render);
case REACT_LAZY_TYPE:
if ((type = 1 === type._status ? type._result : null)) return getComponentName(type);
}
return null;
};