ReactJS-为什么我的嵌套元素没有渲染?

时间:2018-10-09 02:12:52

标签: reactjs

我正在尝试从friendPanel组件内部渲染嵌套组件App。它正在编译,但是在加载时没有显示friendPanel的数组。我是reactJS新手,请耐心等待。我应该如何从App组件中呈现friendPanel?

我的代码的相关部分如下:

class friendPanel extends Component {
  render(props) {
    return (
      <ul>
        {props.friends.map( friend =>
          <li key={friend.id}>{friend.name}</li>
        )}
      </ul>
    );
  }
}

class App extends Component {
  state = { 
    name: 'Bob McBobberson',
    friendList: [
      {id: 1, name: "Sandra"}, 
      {id: 2, name: "Tammy"}, 
      {id: 3, name: "Fernando"}
    ],
  }

  render() {
    return (
      <MuiThemeProvider theme={theme}>
        <div className="App">
          <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <h1>Welcome {this.state.name}</h1>
          </header>
          <friendPanel friends={this.state.friendList} />
        </div>
      </MuiThemeProvider>
    );
  }
}

export default App;

在此先感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

您应该将FriendPanel大写,否则React会将其视为普通的旧HTML。

请参阅:ReactJS component names must begin with capital letters?

答案 1 :(得分:0)

尝试一下:

class FriendPanel extends Component {   //fixed - Component name should start with an upper-case letter
  render() {   // removed the unnecessary props parameter
    return (
      <ul>
        {this.props.friends.map( friend =>  //fixed - in ReactJS, this is the way we get data from props
          <li key={friend.id}>{friend.name}</li>
        )}
      </ul>
    );
  }
}

class App extends Component {
  state = { 
    name: 'Bob McBobberson',
    friendList: [
      {id: 1, name: "Sandra"}, 
      {id: 2, name: "Tammy"}, 
      {id: 3, name: "Fernando"}
    ],
  }

  render() {
    return (
      <MuiThemeProvider theme={theme}>
        <div className="App">
          <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <h1>Welcome {this.state.name}</h1>
          </header>
          <FriendPanel friends={this.state.friendList} />   //fixed -  in JSX, the custom element must start with an upper-case or the compiler will treat this as regular html tag
        </div>
      </MuiThemeProvider>
    );
  }
}