[英]React: custom render method doesn't return the input-label pair
回答。
编辑:这是一个愚蠢的错误,我正在尝试StackOverflow
。
我有一个私有的渲染方法,用来渲染一对 label 和输入。
但是,它没有渲染任何东西。 我几乎尝试了所有方法,但无法弄清楚原因。
这是渲染方法:
const _renderLabelInputPair = (labelValue = '', inputProps = {}) = {
<>
<label>{labelValue}</label>
<input {...inputProps} />
</>
}
清除这种混乱的最简单方法:
圆括号=> 包裹要退回的东西
花括号=> 包裹一个块。
记住其中之一,您就可以开始了!
您还没有从 function 退回任何东西。
您可以执行以下操作之一:
用圆括号替换花括号。
添加一个返回函数,返回整个元素(jsx)。
在 react 函数式组件中,React 期望你返回一些东西。
const _renderLabelInputPair = (labelValue = '', inputProps = {}) = {
return <>
<label>{labelValue}</label>
<input {...inputProps} />
</>
}
我建议您创建一个单独的组件,而不是返回JSX
的 function 。
它将增加您的代码可读性并且更易于维护。
您可以包含return
关键字。 或者使用圆括号作为从箭头函数返回的简写。
此外,还有一个错字 - 将=
更改为=>
const _renderLabelInputPair = (labelValue = '', inputProps = {}) => {
return <>
<label>{labelValue}</label>
<input {...inputProps} />
</>
}
或者
const _renderLabelInputPair = (labelValue = '', inputProps = {}) => (
<>
<label>{labelValue}</label>
<input {...inputProps} />
</>
)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.