[React] 子組件向父組件通信:回調函數

1. 組件間數據通信的單向性

React組件之間的是彼此獨立的,組件間的數據流動是單向的,父組件向子組件通信是最常見的方法,父組件通過props向子組件傳遞需要的信息。

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

const SubComp = ({myProp, myText}) => (
    <span data-myProp={myProp}>{myText}</span>
);

const Page = ({pageProp, pageText}) => (
    <SubComp myProp={pageProp} myText={`myText: ${pageText}`} />
);

ReactDOM.render(
    <Page pageProp={1} pageText={'2'} />,
    document.getElementById('page')
);

2. 子組件向父組件通信

在React中,子組件向父組件通信時,可以使用回調函數,或者自定義事件。
在簡單的場景中,回調函數常用的辦法。

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

const SubComp = ({myProp, myText, setParentState}) => (
    <input type="button"
        data-myProp={myProp}
        onClick={() => setParentState({ text: +new Date })}
        value={myText} />
);

class Page extends Component {
    constructor(props) {
        super(props);

        this.state = {
            text: 1
        };

        this.setParentState = this.setState.bind(this);
    }

    render() {
        return (
            <SubComp
                myProp={this.props.pageProp}
                myText={`myText: ${this.state.text}`}
                setParentState={this.setParentState} />
        );
    }
}

ReactDOM.render(
    <Page pageProp={1} pageText={'2'} />,
    document.getElementById('page')
);

注:
(1)setState是一個異步方法,一個生命周期內所有的setState方法會合并操作。
componentWillMount中執行setState方法,組件會更新state,但是組件只渲染一次。
因此,這是無意義的執行,初始化時的state,都可以放在this.state={...}中。

(2)原生組件的自定義屬性應該加上'data-'前綴,React組件則不需要。

<span myProp={myProp}>{myText}</span>
Warning: Unknown prop `myProp` on <span> tag. Remove this prop from the element.

參考

深入React技術棧 - P74~P75

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容