Javascript 为什么赢了';在这个React render方法中我的简单元素渲染不成功吗?
我得到了一个奇怪的错误: 未捕获错误:对象作为React子对象无效(找到:对象 使用键{element})。如果要呈现一组子对象, 改用数组Javascript 为什么赢了';在这个React render方法中我的简单元素渲染不成功吗?,javascript,reactjs,jsx,Javascript,Reactjs,Jsx,我得到了一个奇怪的错误: 未捕获错误:对象作为React子对象无效(找到:对象 使用键{element})。如果要呈现一组子对象, 改用数组 render(){ const pic=this.props.User.current.pic\u url; let元素; 如果(图片){ 元素=; }否则{ 元素=; } 返回( {element} ) } 只需返回已包含html元素的元素 render () { const pic = this.props.User.current.p
render(){
const pic=this.props.User.current.pic\u url;
let元素;
如果(图片){
元素=;
}否则{
元素=;
}
返回(
{element}
)
}
只需返回已包含html元素的元素
render () {
const pic = this.props.User.current.pic_url;
let element;
if(pic) {
element = <img className = 'MenuPic light' src = {pic}></img>;
} else {
element = <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"/></svg>;
}
return element;
}
render(){
const pic=this.props.User.current.pic\u url;
let元素;
如果(图片){
元素=;
}否则{
元素=;
}
返回元素;
}
返回应该是它的元素。但是通过删除else块来重构代码片段以简化它
render () {
const pic = this.props.User.current.pic_url
if (pic) {
return (<img className='MenuPic light' src={pic} />)
}
return (<svg
xmlns='http://www.w3.org/2000/svg'
height='24'
viewBox='0 0 24 24'
width='24'>
<path d='M0 0h24v24H0V0z' fill='none' />
<path
d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z' />
</svg>)
}
render(){
const pic=this.props.User.current.pic\u url
如果(图片){
返回()
}
返回(
)
}
如果解释器未处于JSX模式,则不需要使用{}around元素
解释器不会进入JSX模式,除非您所在的元素以
开头和结尾
只需删除{}around元素。Do
return元素
,而不是return({element})
。这些花括号正在创建对象文字,而不是从jsx转义。尖括号标记开始和结束jsx,如
中所示。如果在该上下文中使用花括号,这些括号将返回到常规javascript。所以{pic}
意味着“将我返回到常规javascript,并使用变量pic
”。
render () {
const pic = this.props.User.current.pic_url
if (pic) {
return (<img className='MenuPic light' src={pic} />)
}
return (<svg
xmlns='http://www.w3.org/2000/svg'
height='24'
viewBox='0 0 24 24'
width='24'>
<path d='M0 0h24v24H0V0z' fill='none' />
<path
d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z' />
</svg>)
}