我看不到子组件内部的文本。该子项的大小为0x0,并且为空。
这是由路由器引起的吗?
这是我的代码:
App.js:
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import home from './pages/home/home';
import repoDetails from "./pages/repoDetails/repoDetails";
export default class App extends Component {
render() {
return (
<Router>
<Switch>
<Route exact path="/" component={home}/>
<Route path="/:owner/:repo" component={repoDetails}>
</Route>
</Switch>
</Router>
);}}
repoDetails.js:
import React, {Component} from 'react';
import committersCard from '../../components/committersCard.js'
export default class repoDetails extends Component {
render() {
return (
<div>
<committersCard/>
</div>
)}}
这是孩子 committersCard.js:
import React, {Component} from 'react';
export default class committersCard extends Component {
render() {
return (
<div style={{height: '150px', width: '200px'}}>
<h1>TEXT INSIDE THE CHILD COMPONENT</h1>
</div>
);}}
我正在使用React Router 4。
答案 0 :(得分:1)
您的自定义元素必须以大写字母开头,并且您的类名也应该以大写字母开头
repoDetails.js:
import React, {Component} from 'react';
import CommittersCard from '../../components/committersCard.js'
export default class RepoDetails extends Component {
render() {
return (
<div>
<CommittersCard />
</div>
)}}
committersCard.js
import React, {Component} from 'react';
export default class CommittersCard extends Component {
render() {
return (
<div style={{height: '150px', width: '200px'}}>
<h1>TEXT INSIDE THE CHILD COMPONENT</h1>
</div>
);}}*
App.js
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import home from './pages/home/home';
import RepoDetails from "./pages/repoDetails/repoDetails";
export default class App extends Component {
render() {
return (
<Router>
<Switch>
<Route exact path="/" component={home}/>
<Route path="/:owner/:repo" component={RepoDetails} /> //fixed
</Route>
</Switch>
</Router>
);}}
原因是:
当元素类型以小写字母开头时,它指的是 内置组件(例如或),并导致字符串“ div” 或“ span”传递给React.createElement。以a开头的类型 大写字母,例如编译为React.createElement(Foo)和 对应于在JavaScript文件中定义或导入的组件。
我们建议使用大写字母命名组件。如果你有一个 以小写字母开头的组件,请将其分配给 在JSX中使用大写变量之前。
答案 1 :(得分:1)
如果您要使用自定义组件,则它们必须以大写字母开头。
注意:组件名称始终以大写字母开头。
React将以小写字母开头的组件视为DOM标签。 例如,代表HTML div标签,但 代表一个组件,并要求“欢迎”进入范围。
您可以详细了解此约定here背后的原因。
因此,将组件的名称替换为:
import React, {Component} from 'react';
import CommittersCard from '../../components/CommittersCard.js'
export default class RepoDetails extends Component {
render() {
return (
<div>
<CommittersCard/>
</div>
)}}
和
import React, {Component} from 'react';
export default class CommittersCard extends Component {
render() {
return (
<div style={{height: '150px', width: '200px'}}>
<h1>TEXT INSIDE THE CHILD COMPONENT</h1>
</div>
);}}
答案 2 :(得分:0)
经验法则:每个组件名称都应以大写字母开头