react 組件、父子組件傳參、參數(shù)類型限定、默認值設置

一、react 組件的創(chuàng)建和使用

  1. 創(chuàng)建有狀態(tài)組件,創(chuàng)建 src\pages\parent\index.js 組件文件
    有狀態(tài)組件:在無狀態(tài)組件基礎上擁有 this和生命周期
import React, { Component } from 'react';

class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {};
    }
    render() {
        return (
            <>
                <div>Parent</div>
                <div>組件</div>
            </>
        );
    }
}
export default Parent;
  1. 創(chuàng)建無狀態(tài)組件,創(chuàng)建 src\pages\test\index.js 組件文件
    無狀態(tài)組件:無 this 和無生命周期,單純的渲染組件,相比有狀態(tài)組件更高效
    數(shù)據(jù)來源:只能接受父組件傳遞的 props 參數(shù) 和 redux 數(shù)據(jù)
function Test(props) {
    return (
        <>
          <div>{props.msg}</div>
        </>
    );
}

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 (
            <>
                <div>我是Parent組件</div>
                <Child1 title={this.state.title} />
                <div> {this} </div>
            </div>
        );
    }
}

export default Parent;
  1. 創(chuàng)建子組件 src\pages\parent\components\child1.js,在子組件通過 props 屬性 來接收參數(shù),并對參數(shù)類型進行限制和設置默認值
import React, { Component } from 'react';
import PropTypes from 'prop-types';

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

    render() {
        return (
            <>
                <div>我是child1</div>
                <h1>
                    {this.props.title.t1}
                    {this.props.title.t2}
                </h1>
            </>
        );
    }
}

// 對父組件傳遞過來的參數(shù)進行數(shù)據(jù)類型限制
Child1.propTypes = {
    title: PropTypes.object,
};

// 對父組件傳遞過來的參數(shù)進行默認參數(shù)設置
Child1.defaultProps = {
    title: {
        t1: 'default',
        t2: 'props',
    },
};
export default Child1;

2. react 子組件向父組件傳值

  1. 在子組件 src\pages\parent\components\child1.js 中
    子組件通過父組件傳遞過來的屬性方法向父組件傳遞參數(shù)
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 (
            <>
                <div>我是child1</div>
                <h1 onClick={this.handleClick}>
                    {this.props.title.t1}
                    {this.props.title.t2}
                </h1>
            </>
        );
    }
    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 中
    父組件通過在組件標簽上綁定定義的屬性方法來接收子組件傳遞過來的參數(shù)
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 (
            <>
                <div>我是Parent組件</div>
                <Child1 title={this.state.title} changeTitle={this.changeTitle} />
                <h1>{this.state.pTitle}</h1>
            </>
        );
    }
    // 接受子組件傳遞過來的參數(shù)
    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. <MyComponent />).
    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.');
        }
    }),
};
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容