【问题标题】:React.Js - Part of the DOM does not renderReact.Js - 部分 DOM 不呈现
【发布时间】:2021-10-13 01:29:40
【问题描述】:

所以我在这几天开始学习 REACT.JS。

看下面的代码:

import React from 'react'
import ReactDOM from 'react-dom'
import './style.css'
const react = {
    imgSrc: 'https://camo.githubusercontent.com/abd19bd0c5030c8d874ed7073f1815d777004451d5967c447386840b80624569/68747470733a2f2f63646e2e61757468302e636f6d2f626c6f672f72656163742d6a732f72656163742e706e67',
    title: "React",
}
const angular = {
    imgSrc: 'https://upload.wikimedia.org/wikipedia/commons/thumb/c/cf/Angular_full_color_logo.svg/1200px-Angular_full_color_logo.svg.png',
    title: 'Angular',
}
const MyApp = () => {
    return (
        <div>
            <ul>
                <li>
                    <All imgSrc={react.imgSrc} title={react.title} />
                </li>
                <li>
                    <All imgSrc={angular.imgSrc} title={angular.title} />
                </li>
            </ul>
        </div>
    )
}
const All = (props) => {
    return (
        <img src={props.imgSrc} alt="none" />,
        <h1>{props.title}</h1>
    )
}

ReactDOM.render(
    <MyApp />, document.getElementById('root')
)

所以除了 1 件事之外一切都很好

问题

img 标签不渲染。

【问题讨论】:

  • 把组件All 放在MyApp 上面,否则你可能会得到一个引用错误。 All 的返回也是无效的。如果您的意思是返回两个元素,请使用反应片段。目前它正在使用仅返回 h1 元素的逗号
  • 问题解决了 谢谢evolutionbox等人
  • 这能回答你的问题吗? Return multiple elements inside React.render()

标签: javascript reactjs dom jsx


【解决方案1】:

您没有在 All 组件中返回单个 JSX 元素。改为:

const All = (props) => {
    return (
       <div>
        <img src={props.imgSrc} alt="none" />
        <h1>{props.title}</h1>
       </div>
    )
}

或者你可以使用和>代替div,它代表React Fragment

【讨论】:

  • 顺便说一句,这个问题在stackoverflow.com/questions/34893506/…之前有人问过
  • 酷,您可以将问题标记为重复:D
  • (让我们都这样做:D)
  • 刚刚做了 :) 我相信你不需要在每个答案之前评论这个问题,模组会将这个问题标记为重复,即使它只被标记一次。跨度>
  • (好吧,很酷,我只是想让你知道)(顺便说一句,我在耳语)
【解决方案2】:

修复 All 组件的渲染。 逗号运算符从左到右计算并返回最后一条语句。 您基本上只返回 h1 元素。 Comma operator (,)

这是一个工作示例 https://jsfiddle.net/vc5dr9y7/

const All = (props) => {
    return (<React.Fragment>
          <img src={props.imgSrc} alt="none" />
          <h1>{props.title}</h1>
        </React.Fragment>
    )
}

【讨论】:

猜你喜欢
  • 2023-03-05
  • 2020-02-28
  • 2013-06-03
  • 2016-03-13
  • 2014-10-08
  • 1970-01-01
  • 2019-04-22
  • 2023-03-09
  • 2016-04-20
相关资源
最近更新 更多