React 组件传值
使用PubSub模式通信
目录结构如下
App.js:发起网络请求并将返回的结果发布到 mytopic 下
import React from 'react';
import axios from 'axios';
import PubSub from 'pubsub-js'
import ReconnectingWebSocket from "reconnecting-websocket";
import './App.css';
import ShowdetilComponent from './components/Showdetil'
import WebSocketText from './components/WebSocketText'
class App extends React.Component {
mySubscrriber = function(msg, data){
console.log(msg, data);
};
getStudentData = ()=>{
//发起请求
axios.get('http://localhost:3000/react/student').then(
response => {
if(response.status===200){
console.log(response.data);
//发布消息
PubSub.publish('mytopic', response.data);
}
},
error => {console.log('error',error.data);}
);
}
render(){
return (
<div>
<p>hello</p>
//设置点击事件
<button onClick={this.getStudentData}>点击我获取学生数据</button>
<ShowdetilComponent/>
</div>
);
}
}
export default App;
ShowdetilComponent :订阅并展示数据
关于组件生命周期可以参考这篇文章https://www.jianshu.com/p/b331d0e4b398
import React from 'react'
import PubSub from 'pubsub-js'
export default class ShowdetilComponent extends React.Component {
state = {
isChange: false,
peoples: []
}
myTopicCallBack = (msg, data)=>{
console.log(msg+"_sub", data);
this.setState({
isChange: !this.state.isChange,
peoples: data
});
}
// 组件挂载时订阅并设置回调函数
componentDidMount(){
PubSub.subscribe('mytopic',this.myTopicCallBack)
}
render(){
const p1= [<li>123</li>, <li>456</li>,]
const p2 = [
{'name':'小王','age':18,'grade':'高一', 'phone':123456789},
{'name':'小王','age':19,'grade':'高一', 'phone':123456798},
{'name':'小王','age':20,'grade':'高一', 'phone':123456987},
]
const {peoples} = this.state;
console.log('111',peoples);
return (
<ul>
{
peoples.map((people, index)=>{return <li key={people.phone}>{people.name}----{people.age}</li>})
}
</ul>
);
}
}
还有父组件向子组件传值以及子组件向父组件传值请参考 react组件传值的几种方式 - 简书 (jianshu.com)
父组件通过props传递给子组件;
//父组件中
<Child data={[1,2,3]} />
//子组件中
console.log(this.props.data);
子组件传给父组件
父组件通过props向子组件传入一个方法,子组件在通过调用该方法,将数据以参数的形式传给父组件,父组件可以在该方法中对传入的数据进行处理;
//父组件
import Child from './Child.js';
export default class Parent extend compenent{
getData=(data)=>{
console.log(data);
}
render(){
return (
<div>
父组件
<Child getData={this.getData}/>
</div>
)
}
}
子组件给父组件传值
//子组件
export default class Child extend compenent{
state={
data:[1,2,3]
}
render(){
const {data}=this.state;
return (
<div>
//子组件往父组件传值
<button onClick={()=>{this.props.getData(data)}}><button>
</div>
)
}
}
本文来自博客园,作者:糖烤栗子&,转载请注明原文链接:https://www.cnblogs.com/grocerystore/p/15377167.html