react 组件通信方式集合

2019-11-03  本文已影响0人  木中木
  1. 通过props进行父组件 -> 子组件,子组件 ->父组件
export default class  Communicate extends Component{
    constructor() {
        super();
        this.values = ['linjian', 'linjian1', 'linjian2'];
        this.handleChange = this.handleChange.bind(this);
    }

    handleChange() {
        console.log('you click me');
    }

    render() {
        return <>
            <ListOne values = {this.values} handleChange = {this.handleChange} />
        </>
    }

}

class ListOne extends Component {
    render() {
        const {values} = this.props;
        const content = values.map((item) =>{
            return <li>{item}</li>
        })
        return <ul onClick = {this.props.handleChange}>
            {content}
        </ul>
    }
}

  1. 通过context来完成跨级组件传输,这种方式官方不建议,对于构建大型组件,context很难弄明白来自于哪里
class List extends Component {
    static childContextTypes = {
        color: checkPropTypes.func,
        backgroundColor: checkPropTypes.string,
    }

    getChildContext() {
        return {
            backgroundColor: 'blue',
            color: () => 'red',
        }
    }

    render(){
        return <ul>
            <SumItem></SumItem>
        </ul>      
    }
}

class SumItem extends Component {
    static contextTypes  = {
        backgroundColor: checkPropTypes.string,
    }
    render() {
        return <li style={{background: this.context.backgroundColor}}>
            <TextItem/>
        </li>   
    }
}

class TextItem extends Component {
    static contextTypes  = {
        color: checkPropTypes.func,
    }
    render() {
        return <label style={{color: this.context.color()}}>test</label>   
    }
}
  1. 通过发布/订阅模式来举例,EventEmitter,这种方式和reactNative中提供通信一样
export default class  Communicate extends Component{
    constructor() {
        super();
        this.values = ['linjian', 'linjian1', 'linjian2'];
        this.handleChange = this.handleChange.bind(this);
    }

    handleChange() {
        console.log('you click me');
    }

    componentDidMount() {
        this.itemClick = emitter.on('itemClick', (data) => {
            console.log(data);
        })
    }

    componentWillUnmount() {
        emitter.removeListener(this.itemClick);
    }

    render() {
        return <>
            <ListOne values = {this.values} handleChange = {this.handleChange} />
            <List/>
        </>
    }

}

class SumItem extends Component {
    static contextTypes  = {
        backgroundColor: checkPropTypes.string,
    }
    render() {
        return <li style={{background: this.context.backgroundColor}} onClick = {()=> emitter.emit('itemClick', 'test')}>
            <TextItem/>
        </li>   
    }
}

上一篇 下一篇

猜你喜欢

热点阅读