1. 程式人生 > 其它 >元件間的通訊

元件間的通訊

元件之間的通訊

每個元件之間都是獨立的,但是它們之間也存在關係,存在關係就需要通訊;

元件之間的通訊也會看元件之間是什麼關係,這裡先介紹只基於React父子元件之間的簡單通訊:

在React中父子元件通訊是基於一個屬性props,子元件會從父元件那裡接收屬性,函式等;

01-props傳遞屬性

父元件

class Father extends Component {
    constructor(props) {
        super(props)

        this.state = {
            name: "張三",
            age: 19,
            height: 1.88,
        }
    }


    render() {
        return (
            <div>
                <Child name={this.state.name} age={this.state.age} height={this.state.height} />
            </div>
        )
    }
}

子元件

function Child(props) {
    const { name, age, height } = props;

    return (
        <div>
            <div>名字:{name} 年齡:{age} 身高:{height}</div>
        </div>
    )
}

我們只需要在使用元件的時候往‘裡面’塞值就行了,但是有個注意點,有些屬性是不歸props管的,例如:ref,key等,這些屬性是不會隨著props向下傳遞的;

02-props傳遞函式

上面我們講解了props傳遞屬性,props傳遞函式是讓父子元件相互之間響應的關鍵;

簡單講下業務邏輯:父元件有一個屬性counter,這個屬性會子元件裡面的button點選而增加

父元件

 class App extends Component {
    constructor(props) {
        super(props)

        this.state = {
            counter: 0
        }
    }

    increment() {
        this.setState({
            counter: ++this.state.counter
        })
    }

    render() {
        return (
            <div>
                <p>{this.state.counter}</p>
                {/* 記住需要繫結this,其他的都和基本資料型別相同*/}
                <Child increment={e => this.increment()}></Child>
            </div>
        )
    }
}

子元件:

function Child(props) {
    const {increment} = props;

    return (
        <button onClick={increment}>+</button>
    );
}

注意一下this的繫結就行了

03-props傳遞時的型別檢測

在react腳手架裡面集成了prop-types這個模組;

直接引用就完事了

import PropType from "prop-types"
// 此時的Child元件是函式式元件
// 為Child的props進行型別檢測
Child.propTypes = {
    // isRequired是將這個屬性置為必須傳入的
    name: PropType.string.isRequired,
    age: PropType.number,
    height: PropType.number,
    names: PropType.array,
};

// 為Child元件新增預設值,並且即使設定了isRequired也不會報警告
Child.defaultProps = {
    name: "lsq",
    age: 18,
    height: 1.84,
    names: ["小闖", "小猛", "小攀"],
};

類元件直接在類元件內部新增static

export default class App extends Component {
		...
		static propTypes = {...}
   	static defaultProps = {...}
		...
}

至於其他的元件通訊,我們後面再講
完整程式碼,請到git倉庫找