剧场模式
首页前端React诱人的 react 视频教程-基础篇

诱人的 react 视频教程 - 基础篇 #6 通过 Props 传递数据

海外散仙厉飞雨 · 真仙发布于

学到的知识点:

  1. this.props

  2. this.props.children

  3. Typechecking With PropTypes https://reactjs.org/docs/typechecking-with-proptypes.html

src/App.js

import React, { Component } from 'react';

import Header from './components/Header';
import Home from './components/Home';

class App extends Component {
  render() {
    const user = {
      name: "Anna",
      hobbies: ["Sports", "Reading"]
    }
    return (
      <div className="container">
        <div className="row">
          <div className="col-xs-1 col-xs-offset-11">
            <Header />
          </div>
        </div>
        <div className="row">
          <div className="col-xs-1 col-xs-offset-11">
            <h1>Hello !!</h1>
          </div>
        </div>
        <div className="row">
          <div className="col-xs-1 col-xs-offset-11">
            <Home name={"Max"} age={12} user={user}>
              <p>I am child</p>
            </Home>
          </div>
        </div>
      </div>
    );
  }
}

export default App;

src/components/Home.js

import React, { Component } from 'react';

import PropTypes from 'prop-types';

export default class Home extends Component {
  render() {
    return (
      <div className="container">
        <div className="row">
          <div className="col-xs-1 col-xs-offset-11">
            <div>your name is {this.props.name}, your age is {this.props.age}</div>
            <div>
              <h4>hobbies</h4>
              <ul>
                {this.props.user.hobbies.map((hobby, i) => <li key={i}>{hobby}</li>)}
              </ul>
            </div>
            <div>{this.props.children}</div>
          </div>
        </div>
      </div>
    );
  }
}

Home.propTypes = {
  name: PropTypes.string,
  age: PropTypes.number,
  user: PropTypes.object,
  children: PropTypes.element.isRequired
};
9 条回复

© 汕尾市求知科技有限公司 | 粤ICP备19038915号 | 在线学员:103

Top