網站首頁 編程語言 正文
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="..."
/> <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)
- 一種組件間通信的方式,適用于任意組件間通信。
- 使用步驟:
- 安裝pubsub:npm i pubsub-js
- 引入: import PubSub from ‘pubsub-js’
- 接收數據:A組件想接收數據,則在A組件中訂閱消息,訂閱的回調留在A組件自身
methods(){
demo(data){…}
}
mounted() {
this.pid = PubSub.subscribe(‘xxx’,this.demo) //訂閱消息
}- 提供數據:PubSub.publish(‘xxx’,數據)
- 最好在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="..."
/> <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>
);
}
}
原文鏈接:https://blog.csdn.net/weixin_50379372/article/details/131341428
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2023-07-16 uniapp 小程序 filters 過濾日期
- 2022-12-06 深入了解Rust?結構體的使用_Rust語言
- 2022-05-06 SQL查看表字段信息如:字段名、字段類型、字段精度、字段大小、索引、主鍵等
- 2022-07-01 c++詳細講解構造函數的拷貝流程_C 語言
- 2022-02-15 使用數組的sort方法完成項目中的排序功能(數組sort方法與chart圖表展示結合)
- 2022-06-18 android自定義滾動上下回彈scollView_Android
- 2022-09-19 .Net?Core使用layui多文件上傳_實用技巧
- 2023-01-14 Go?Map并發沖突預防與解決_Golang
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支