Front End

[React] 子组件向父组件通信:回调函数

2016-12-21  本文已影响369人  何幻

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

上一篇 下一篇

猜你喜欢

热点阅读