3阶段

4 - 组件 & props

2019-02-26  本文已影响184人  Elvmx

组件可以将UI切分成一些独立的、可复用的部件,这样你就只需专注于构建每一个单独的部件。

组件从概念上看就像是函数,它可以接收任意的输入值(称之为“props”),并返回一个需要在页面上展示的React元素。

定义组件

  1. 函数定义
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
  1. 类定义
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

使用组件

// 1. 引入
import App from './App';
// 2. 使用 ReactDOM.render 渲染
ReactDOM.render(<App />, document.getElementById('root'));

组合组件

ReactDOM.render(
  <div>
    <Component1 />
    <Component2 />
  </div>,
  document.getElementById('root')
);

组件嵌套

// com1.js

class Com1 extends Component {
  render() {
    return (
      <div>我是 com1 组件</div>
    )
  }
}

// com2.js
import Com1 from './com1.js';

class Com2 extends Component {
  render() {
    return (
      <div>
        <h1>我是 com2 组件</h1>

        <Com1 />
      </div>
    )
  }
}

props

当React遇到的元素是用户自定义的组件,它会将JSX属性作为单个对象传递给该组件,这个对象称之为“props”。

props 的只读性

所有的React组件必须像纯函数那样使用它们的props。

props 的校验

  1. 安装 prop-types 模块
  2. 定义 组件的静态属性 propTypes
import PropTypes from 'prop-types';

// 类组件
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
Welcome.propTypes = {
  name: PropTypes.string
}

// 函数组件
const Hello = (props) => <h1>hello, { props.name }</h1>
Hello.propTypes = {
  name: PropTypes.number
}

https://reactjs.org/docs/typechecking-with-proptypes.html#proptypes

props 的默认值

定义 组件的静态属性 defaultProps

// 类组件
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
Welcome.defaultProps = {
  name: '张三'
}

// 函数组件
const Hello = (props) => <h1>hello, { props.name }</h1>
Hello.defaultProps = {
  name: 2
}

纯函数

原则:

  1. 不会改变参数
  2. 相同的输入一定产生相同的输出

如下就是一个纯函数:

function sum(a, b) {
  return a + b;
}

如下就是一个不纯的函数:

function hello(a, b) {
  return Math.random() + a - b;
}
上一篇 下一篇

猜你喜欢

热点阅读