react 组件、父子组件传参、参数类型限定、默认值设置

一、react 组件的创建和使用

  1. 创建有状态组件,创建 src\pages\parent\index.js 组件文件
    有状态组件:在无状态组件基础上拥有 this和生命周期
import React, { Component } from 'react';

class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {};
    }
    render() {
        return (
            <>
                
Parent
组件
); } } export default Parent;
  1. 创建无状态组件,创建 src\pages\test\index.js 组件文件
    无状态组件:无 this 和无生命周期,单纯的渲染组件,相比有状态组件更高效
    数据来源:只能接受父组件传递的 props 参数 和 redux 数据
function Test(props) {
    return (
        <>
          
{props.msg}
); } export default Test;

二、react 父子组件传值

1. react 父组件向子组件传值

  1. 在父组件 src\pages\parent\index.js 中,通过在组件标签上绑定属性来传参
import React, { Component } from 'react';
import Child1 from './components/child1';

class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            title: {
                t1: '云想衣裳',
                t2: '花想容',
            }
        };
    }

    render() {
        return (
            <>
                
我是Parent组件
{this}
); } } export default Parent;
  1. 创建子组件 src\pages\parent\components\child1.js,在子组件通过 props 属性 来接收参数,并对参数类型进行限制和设置默认值
import React, { Component } from 'react';
import PropTypes from 'prop-types';

class Child1 extends Component {
    constructor(props) {
        super(props);
        this.state = {};
    }

    render() {
        return (
            <>
                
我是child1

{this.props.title.t1} {this.props.title.t2}

); } } // 对父组件传递过来的参数进行数据类型限制 Child1.propTypes = { title: PropTypes.object, }; // 对父组件传递过来的参数进行默认参数设置 Child1.defaultProps = { title: { t1: 'default', t2: 'props', }, }; export default Child1;

2. react 子组件向父组件传值

  1. 在子组件 src\pages\parent\components\child1.js 中
    子组件通过父组件传递过来的属性方法向父组件传递参数
import React, { Component } from 'react';
import PropTypes from 'prop-types';

class Child1 extends Component {
    constructor(props) {
        super(props);
        this.state = {
            pTitle: '春风拂槛露华浓',
        };
        this.handleClick = this.handleClick.bind(this);
    }

    render() {
        return (
            <>
                
我是child1

{this.props.title.t1} {this.props.title.t2}

); } handleClick() { // 子组件向父组件传参 this.props.changeTitle(this.state.pTitle); } } Child1.propTypes = { title: PropTypes.object, }; Child1.defaultProps = { title: { t1: 'default', t2: 'props', }, }; export default Child1;
  1. 在父组件 Parent.js 中
    父组件通过在组件标签上绑定定义的属性方法来接收子组件传递过来的参数
import React, { Component } from 'react';
import Child1 from './components/child1';

class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            title: {
                t1: '云想衣裳',
                t2: '花想容',
            },
            pTitle: '',
        };
        this.changeTitle = this.changeTitle.bind(this); // 指定this指向
    }

    render() {
        return (
            <>
                
我是Parent组件

{this.state.pTitle}

); } // 接受子组件传递过来的参数 changeTitle(pTitle) { this.setState(() => { return { pTitle, }; }); } } export default Parent;

三、propTypes 参考资料

import React from 'react';
import PropTypes from 'prop-types';

class MyComponent extends React.Component {
    render() {
        // ... do things with the props
    }
}

MyComponent.propTypes = {
    // You can declare that a prop is a specific JS primitive. By default, these
    // are all optional.
    optionalArray: PropTypes.array,
    optionalBigInt: PropTypes.bigint,
    optionalBool: PropTypes.bool,
    optionalFunc: PropTypes.func,
    optionalNumber: PropTypes.number,
    optionalObject: PropTypes.object,
    optionalString: PropTypes.string,
    optionalSymbol: PropTypes.symbol,

    // Anything that can be rendered: numbers, strings, elements or an array
    // (or fragment) containing these types.
    // see https://reactjs.org/docs/rendering-elements.html for more info
    optionalNode: PropTypes.node,

    // A React element (ie. ).
    optionalElement: PropTypes.element,

    // A React element type (eg. MyComponent).
    // a function, string, or "element-like" object (eg. React.Fragment, Suspense, etc.)
    // see https://github.com/facebook/react/blob/HEAD/packages/shared/isValidElementType.js
    optionalElementType: PropTypes.elementType,

    // You can also declare that a prop is an instance of a class. This uses
    // JS's instanceof operator.
    optionalMessage: PropTypes.instanceOf(Message),

    // You can ensure that your prop is limited to specific values by treating
    // it as an enum.
    optionalEnum: PropTypes.oneOf(['News', 'Photos']),

    // An object that could be one of many types
    optionalUnion: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.instanceOf(Message)]),

    // An array of a certain type
    optionalArrayOf: PropTypes.arrayOf(PropTypes.number),

    // An object with property values of a certain type
    optionalObjectOf: PropTypes.objectOf(PropTypes.number),

    // You can chain any of the above with `isRequired` to make sure a warning
    // is shown if the prop isn't provided.

    // An object taking on a particular shape
    optionalObjectWithShape: PropTypes.shape({
        optionalProperty: PropTypes.string,
        requiredProperty: PropTypes.number.isRequired,
    }),

    // An object with warnings on extra properties
    optionalObjectWithStrictShape: PropTypes.exact({
        optionalProperty: PropTypes.string,
        requiredProperty: PropTypes.number.isRequired,
    }),

    requiredFunc: PropTypes.func.isRequired,

    // A value of any data type
    requiredAny: PropTypes.any.isRequired,

    // You can also specify a custom validator. It should return an Error
    // object if the validation fails. Don't `console.warn` or throw, as this
    // won't work inside `oneOfType`.
    customProp: function (props, propName, componentName) {
        if (!/matchme/.test(props[propName])) {
            return new Error('Invalid prop `' + propName + '` supplied to' + ' `' + componentName + '`. Validation failed.');
        }
    },

    // You can also supply a custom validator to `arrayOf` and `objectOf`.
    // It should return an Error object if the validation fails. The validator
    // will be called for each key in the array or object. The first two
    // arguments of the validator are the array or object itself, and the
    // current item's key.
    customArrayProp: PropTypes.arrayOf(function (propValue, key, componentName, location, propFullName) {
        if (!/matchme/.test(propValue[key])) {
            return new Error('Invalid prop `' + propFullName + '` supplied to' + ' `' + componentName + '`. Validation failed.');
        }
    }),
};

你可能感兴趣的:(react 组件、父子组件传参、参数类型限定、默认值设置)