美文网首页
组件间通信

组件间通信

作者: 努力生活的西鱼 | 来源:发表于2019-03-18 09:40 被阅读0次
    React Native

    组件间通信

    父组件向子组件通信,子组件之间通信
    • 父组件以自身的state作为作为子组件的props;父组件调用setState,于是子组件的props相应变化。
    • Component中若使用state而不是props渲染,则需使用componentWillReceiveProps生命周期
    • 通过ref调用子组件的方法
    ref
    // 推荐写法
    class App extends Component {
        render() {
            return(
                <CountDown ref= {instance => this.countDown = instance}/>
            )
        }
    
        componentDidMount() {
            this.countDown.add(10086);
        }
    }
    
    // 不推荐写法
    class App extends Component {
        render() {
            return(
                <CountDown ref= "countDown"/>
            )
        }
    
        componentDidMount() {
            this.refs.countDown.add(10086);
        }
    }
    
    例子(通过ref获取子控件,进行通信)
    import React, {Component} from 'react';
    import {
        StyleSheet,
        Text,
        View,
        TouchableOpacity
    } from 'react-native';
    
    export default class App extends Component<Props> {
        render() {
            return (
                <View style={styles.container}>
                    <TouchableOpacity onPress={this.addTime}>
                        <Text>延长10秒</Text>
                    </TouchableOpacity>
                    {/*参数为CountDown的实例*/}
                    <CountDown ref={countDown => this.countDown = countDown}/>
                </View>
            );
        }
    
        addTime = () => {
            this.countDown.add(10);
        }
    
    
    }
    
    class CountDown extends Component {
        state = {
            count: 30,
        };
    
        render() {
            const {count} = this.state;
            return (
                <Text>{count}</Text>
            )
        }
    
        add = (time) => {
            this.setState({
                count: this.state.count + time,
            });
        }
    
        componentDidMount() {
            this.timer = setInterval(() => {
                const {count} = this.state;
                if (count === 0) {
                    return clearInterval(this.timer);
                }
                this.setState({
                    count: count - 1,
                });
            }, 1000);
        }
    
        componentWillUnmount(): void {
            clearInterval(this.timer);
        }
    
    }
    
    
    const styles = StyleSheet.create({
        container: {
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: '#F5FCFF',
        },
    });
    
    子组件向父组件通信
    • 父组件将函数作为props传递给子组件,子组件在需要时调用,将数据作为函数参数传回。
    • 此谓之“回调”(callback)
    export default class App extends Component<Props> {
        render() {
            return (
                <View style={styles.container}>
                    <CountDown timeupParent={this.timeupParent}/>
                </View>
            );
        }
    
        timeupParent = (param) => {
            alert("parent know:" + param);
        }
    
    }
    
    class CountDown extends Component {
        state = {
            count: 10,
        };
    
        render() {
            const {count} = this.state;
            return (
                <Text>{count}</Text>
            )
        }
    
        timeUp = () => {
            // 防止函数不存在
            this.props.timeupParent && this.props.timeupParent(123);
        }
    
        componentDidMount() {
            this.timer = setInterval(() => {
                const {count} = this.state;
                if (count === 0) {
                    this.timeUp();
                    return clearInterval(this.timer);
                }
                this.setState({
                    count: count - 1,
                });
            }, 1000);
        }
    
        componentWillUnmount(): void {
            clearInterval(this.timer);
        }
    
    }
    
    
    const styles = StyleSheet.create({
        container: {
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: '#F5FCFF',
        },
    });
    
    动态列表的回调函数参数
    arr.map(d => <Text key={d.id} onPress={() => this.handlePress(d.text)}>{d.text}</Text>)
    
    arr.map(d => <Text key={d.id} onPress={this.handlePress.bind(this,d.id)}>{d.text}</Text>)
    

    箭头函数或bind都会生成新函数。传入参数以闭包的形式"封存",留待调用。

    export default class App extends Component<Props> {
    
        state = {
            arr: [1,2,3]
        }
    
        render() {
            return (
                <View style={styles.container}>
                    {
                        this.state.arr.map( i => {
                            return <CountDown key={i} timeupParent={(child) => this.timeupParent("父组件用于区分的参数:" + i,child)}/>
                        })
                    }
                </View>
            );
        }
    
        timeupParent = (param1,param2) => {
            alert("parent know:" + param1);
            alert("parent know:" + param2);
        }
    
    }
    
    class CountDown extends Component {
        state = {
            count: 10,
        };
    
        render() {
            const {count} = this.state;
            return (
                <Text>{count}</Text>
            )
        }
    
        timeUp = () => {
            this.props.timeupParent("子组件传回的参数:" + 123);
        }
    
        componentDidMount() {
            this.timer = setInterval(() => {
                const {count} = this.state;
                if (count === 0) {
                    this.timeUp();
                    return clearInterval(this.timer);
                }
                this.setState({
                    count: count - 1,
                });
            }, 1000);
        }
    
        componentWillUnmount(): void {
            clearInterval(this.timer);
        }
    
    }
    
    
    const styles = StyleSheet.create({
        container: {
            flex: 1,
            justifyContent: 'center',
            alignItems: 'center',
            backgroundColor: '#F5FCFF',
        },
    });
    

    任意组件(跨越父子)之间的通信

    • 全局事件订阅系统(EventEmitter)
    • (Flux系)单向数据流框架
      • flux
      • reflux
      • alt
      • redux
    • 双向数据流框架
      • mobx 1

    相关文章

      网友评论

          本文标题:组件间通信

          本文链接:https://www.haomeiwen.com/subject/eqgmmqtx.html