javascript - React 不渲染称为 HTML 的函数
问题描述
作为我的 React 应用程序的一部分,箭头函数ContainerCookiesPolicy
调用箭头函数LogInTitleTest
(以及其他一些函数)。
export default class MyClass extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
ContainerCookiesPolicy = () => {
if (window.localStorage.getItem('CookiesAgreed') !== 'true') {
return (
<div className='ContainerCookiesPolicy'>
<this.LogInTitleTest/>
{/*Some other functions*/}
</div>
)
} else {
return null;
}
}
LogInTitleTest = () => {
return (
<span className='Log_in_title_text'>{'Text'}</span>
);
}
render() {
<this.ContainerCookiesPolicy/>
{/*Some other functions*/}
}
}
如果我执行这段代码,即函数ContainerCookiesPolicy
调用函数LogInTitleTest
,React 将不会渲染任何东西(就像你的函数/对象返回时那样null
)并且会给出错误Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.
。但是,如果我改为复制并粘贴 LogInTitleTest
里面的内容,ContainerCookiesPolicy
如下所示:
ContainerCookiesPolicy = () => {
if (window.localStorage.getItem('CookiesAgreed') !== 'true') {
return (
<div className='ContainerCookiesPolicy'>
<span className='Log_in_title_text'>{'Text'}</span>
{/*Some other functions*/}
</div>
)
} else {
return null;
}
}
它实际上会呈现带有单词的整个页面Text
。
进一步的考虑:
- 如果我的函数
LogInTitleTest
包含<div>
相反,它也不会呈现页面;如果<div>
包含在 functionContainerCookiesPolicy
中,它将呈现。如果不是{'Text'}
我只有Text
.
LogInTitleTest = () => {
return (
<div className="Log_in_title_container">
<span className='Log_in_title_text'>{'Text'}</span>
</div>
);
}
- 如果我将函数更改
LogInTitleTest
为 returnnull
,情况将保持不变:
LogInTitleTest = () => {
return null;
}
我正在使用 AWS Amplify 呈现页面。在本地主机上的 WebStorm 上,我没有观察到这种奇怪的行为。
LogInTitleTest
我在另一部分代码上测试了原始函数,它按预期工作。因此,问题必须与ContainerCookiesPolicy
.
知道为什么会这样吗?任何帮助,将不胜感激!
提前致谢
解决方案
您不应该将组件引用为<this.LogInTitleTest />
. 应该是<LogInTitleTest />
。
如果它们在单个文件中,还要注意定义功能组件的顺序。如本问题所述,箭头函数是自上而下评估的。
const LogInTitleTest = () => {
return (
<span className='Log_in_title_text'>{'Text'}</span>
);
}
const ContainerCookiesPolicy = () => {
if (window.localStorage.getItem('CookiesAgreed') !== 'true') {
return (
<div className='ContainerCookiesPolicy'>
<LogInTitleTest />
{/*Some other functions*/}
</div>
)
} else {
return null;
}
}
编辑:基于更新问题的更新
现在您已经更新了示例,很明显您正在使用类组件。要在类组件中渲染 JSX 块,您通常将函数称为函数而不是组件。
另请注意,您的示例中的渲染函数当前未返回任何内容。
export default class MyClass extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
renderContainerCookiesPolicy = () => {
if (window.localStorage.getItem('CookiesAgreed') !== 'true') {
return (
<div className='ContainerCookiesPolicy'>
{this.renderLogInTitleTest()}
{/*Some other functions*/}
</div>
)
} else {
return null;
}
}
renderLogInTitleTest = () => {
return (
<span className='Log_in_title_text'>Text</span>
);
}
render() {
return (
{this.renderContainerCookiesPolicy()}
{/*Some other functions*/}
)
}
}