react父子组件,任意组件传值

react类组件 父组件给子组件传值,子组件使用props接收

// 子组件Main 
import React from "react";
import PropTypes from 'prop-types';
class Main extends React.Component {
    /* 属性规则校验 */
    static defaultProps = {
        xNum: 0,
        bigNum: 0
    };
    static propTypes = {
        xNum: PropTypes.number,
        bigNum: PropTypes.number
    };

    render() {
        let { xNum, bigNum} = this.props;
        return <div className="main">
            <p>邓紫棋有:{bigNum}专辑</p>
            <p>周杰伦有:{xNum}首歌</p>
        </div>;
    }
}

export default Main;
// 子组件Footer 
import React from "react";
import { Button } from 'antd';
import PropTypes from 'prop-types';

class Footer extends React.PureComponent {
    /* 属性规则校验 */
    static defaultProps = {};
    static propTypes = {
        change: PropTypes.func.isRequired
    };

    render() {
        let { change } = this.props;
        return <div className="footer">
            <Button type="primary" onClick={change.bind(null, 'sup')}>你好</Button>
            <Button type="primary" danger onClick={change.bind(null, 'opp')}>我不好</Button>
        </div>;
    }
}

export default Footer;
// 父组件
import React from "react";
import Main from './Main';  // 引入子组件
import Footer from './Footer';  // 引入子组件

class Wei extends React.Component {
    state = {
        bigNum: 10,
        xNum : 0
    };

    // 设置为箭头函数:不论方法在哪执行的,方法中的this永远都是Wei父组件的实例
    change = (type) => {
        let { bigNum, xNum } = this.state;
        if (type === 'big') {
            this.setState({ bigNum: bigNum+ 1 });
            return;
        }
        this.setState({ xNum : xNum + 1 });
    };

    render() {
        let { bigNum, xNum } = this.state;
        return <div>
            <div className="header">
                <span className="num">{bigNum+ xNum }</span>
            </div>
            <Main  bigNum={bigNum} xNum ={xNum} />
            <Footer  change={this.change} />
        </div>;
    }
}

export default Wei;

react类组件 子组件给父组件传值,父组件先给子组件传一个函数,子组件通过调用这个方法传递参数

子组件

import React, { Component } from 'react';
import './index.css';
//引入axios
import axios from 'axios';
export default class Seach extends Component {
	getEached = () => {
		//console.log(this.Eache.value)
		//解构赋值
		const { value } = this.Eache;
		console.log(value);

		//请求之前
		this.props.undate({ isFirst: false, isLoading: true });

		axios.get(`http://localhost:3000/api1/search/users?q=${value}`).then(
			(response) => {
		//请求成功后
				this.props.undate({ isFirst: false, isLoading: false, sum: response.data.items });
			},
			(error) => {
		//请求失败
				this.props.undate({ isFirst: false, isLoading: false, err: error.message });
			}
		);
	};
	render() {
		return (
			<div>
				<section className="jumbotron">
					<h3 className="jumbotron-heading">发送请求</h3>
					<div>
						<input
							type="text"
							ref={(a) => {
								return (this.Eache = a);
							}}
							placeholder="..."
						/>&nbsp;<button onClick={this.getEached}>查询</button>
					</div>
				</section>
			</div>
		);
	}
}

父组件

import React, { Component } from 'react';
import './app.css';
//引入子组件
import List from './components/List';
import Seach from './components/Seach';
export default class App extends Component {
	//初始化状态
	state = {
		sum: [],
		isFirst: true, //是否为第一次打开页面
		isLoading: false, //标识是否处于加载中
		err: '' //存储请求相关错误信息
	};

	//更新数据
	undate = (dataObj) => {
		this.setState(dataObj);
	};
	render() {
		const { sum } = this.state;
		return (
			<div>
				<div className="container">
					<Seach undate={this.undate} />
					<List {...this.state} />
				</div>
			</div>
		);
	}
}

react类组件 任意组件传值,消息订阅与发布(pubsub)

  1. 一种组件间通信的方式,适用于任意组件间通信。
  2. 使用步骤:
  3. 安装pubsub:npm i pubsub-js
  4. 引入: import PubSub from ‘pubsub-js’
  5. 接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身
    methods(){
    demo(data){…}
    }
    mounted() {
    this.pid = PubSub.subscribe(‘xxx’,this.demo) //订阅消息
    }
  6. 提供数据:PubSub.publish(‘xxx’,数据)
  7. 最好在beforeDestroy钩子中,用PubSub.unsubscribe(pid)取消订阅。
    */
兄弟组件Seach

import React, { Component } from 'react';
import './index.css';
//引入axios
import axios from 'axios';
//引入消息订阅与发布包
import PubSub from 'pubsub-js'
export default class Seach extends Component {
	getEached = () => {
		//console.log(this.Eache.value)
		//解构赋值
		const { value } = this.Eache;
		console.log(value);

		//请求之前,发布消息
		PubSub.publish('wangyihuan',{ isFirst: false, isLoading: true })

		axios.get(`http://localhost:3000/api1/search/users?q=${value}`).then(
			(response) => {
		//请求成功后
		PubSub.publish('wangyihuan',{ isFirst: false, isLoading: false, sum: response.data.items })
			
			},
			(error) => {

		 //请求失败
		 PubSub.publish('wangyihuan',{ isFirst: false, isLoading: false, err: error.message })				
			}
		);
	};
	render() {
		return (
			<div>
				<section className="jumbotron">
					<h3 className="jumbotron-heading">发送请求</h3>
					<div>
						<input
							type="text"
							ref={(a) => {
								return (this.Eache = a);
							}}
							placeholder="..."
						/>&nbsp;<button onClick={this.getEached}>查询</button>
					</div>
				</section>
			</div>
		);
	}
}

兄弟组件List

import React, { Component } from 'react';
import './index.css';
//引入消息订阅与发布包
import PubSub from 'pubsub-js'
export default class List extends Component {
   	//初始化状态
	state = {
		sum: [],
		isFirst: true, //是否为第一次打开页面
		isLoading: false, //标识是否处于加载中
		err: '' //存储请求相关错误信息
	};

	//挂载完毕,订阅消息
	componentDidMount(){
		// 语法:回调函数中必须为两个参数(a,data),a:代表返回的事件名,data为传回来的数据,还有这快必须写成箭头函数
	this.tokens= PubSub.subscribe('wangyihuan',(a,data)=>{
	 this.setState(data)
		})
	}
	//销毁订阅
	componentWillUnmount(){
		PubSub.unsubscribe(this.tokens);
	}
	render() {
		const { sum,isFirst,isLoading, err} = this.state;
		return (
			<div>                                                             
				{                                   
					isFirst ? <h2>你好邓紫棋,欢迎您!!!</h2>:
					isLoading ? <h2>loading...</h2> : 
					err ? <h2>{err}</h2> : 					
					sum.map((item) => {
					return (
						<div key={item.id} className="row">
							<div className="card">
								<a href={item.html_url} rel="noreferrer" target="_blank">
									<img
										alt="avatar"
										src={item.avatar_url}
										style={{ width: '100px' }}
									/>
								</a>
								<p className="card-text">{item.login}</p>
							</div>
						</div>
					);
				})}
			</div>
		);
	}
}

你可能感兴趣的:(react.js,react.js,javascript,ecmascript)