>首页> IT >

react通信有哪些方式

时间:2022-03-22 14:52:44       来源:PHP中文网

本教程操作环境:Windows7系统、react17.0.1版、Dell G3电脑。

React的六种通信方式

1.props父子通信

function Children(props) {      return (        

Children

{props.text}

) } function Parent() { return (

Parent

) } export default Parent

2.回调函数,子父通信

function Children(props) {  return (    

Children

{props.text}

)}function Parent() { let [text, setText] = useState("这是爸爸传给你的东西") function handleChange(val) { setText(val) } return (

Parent

)}export default Parent

3.变量提升,兄弟组建通信

function Children(props) {  return (    

Children

)}function Children1(props) { return (

Children1

{props.text}

)}function App() { let [text, setText] = useState("") return ( <>
APP
)}export default App

4.Context,跨组建通信

旧写法

class Children extends React.Component {  static contextTypes = {    text: PropsType.string  }  render() {    return (      

Children

{this.context.text}

) }}class Parent extends React.Component { static childContextTypes = { text: PropsType.string } getChildContext() { return { text: "我是爸爸的信息" } } render() { return (

Parent

) }}export default Parent

新写法

const { Consumer, Provider } = React.createContext()class Children extends React.Component {  render() {    return (              {          (value) => (            

Children1

{value.text}

) }
) }}class Parent extends React.Component { render() { return (

Parent

) }}export default Parent

5.node的events模块的单例通信

function Children(props) {  return (    

Children

{props.text}

)}function Parent() { let [text, setText] = useState("这是爸爸传给你的东西") let event = new Events() event.on("foo", () => { setText("改变了") }) return (

Parent

)}export default Parent

注意⚠️:这种通信记住在顶部引入events模块,无需安装,node自身模块。

6.redux共享数据通信

store.js

import { createStore } from "redux"let defaultState = {    text: "我是store"}let reducer = (state = defaultState, action) => {    switch (action) {        default: return state    }}export default createStore(reducer)

child.js

import React from "react"import { connect } from "react-redux"class Child extends React.Component {    render() {        return (            
Child

{this.props.text}

) }}let mapStataToProps = (state) => { return { text: state.text }}export default connect(mapStataToProps, null)(Child)

Parent.js

class Parent extends React.Component {  render() {    return (              

Parent

) }}export default Parent

注意:记得安装reduxreact-redux

【相关推荐:Redis视频教程】

以上就是react通信有哪些方式的详细内容,更多请关注php中文网其它相关文章!

关键词: 相关文章 数据通信 视频教程