本教程操作环境:Windows7系统、react17.0.1版、Dell G3电脑。
React的六种通信方式
1.props父子通信
function Children(props) { return () } function Parent() { return (Children
{props.text}
) } export default ParentParent
2.回调函数,子父通信
function Children(props) { return ()}function Parent() { let [text, setText] = useState("这是爸爸传给你的东西") function handleChange(val) { setText(val) } return (Children
{props.text}
)}export default ParentParent
3.变量提升,兄弟组建通信
function Children(props) { return ()}function Children1(props) { return (Children
)}function App() { let [text, setText] = useState("") return ( <>Children1
{props.text}
APP> )}export default App
4.Context,跨组建通信
旧写法
class Children extends React.Component { static contextTypes = { text: PropsType.string } render() { return () }}class Parent extends React.Component { static childContextTypes = { text: PropsType.string } getChildContext() { return { text: "我是爸爸的信息" } } render() { return (Children
{this.context.text}
) }}export default ParentParent
新写法
const { Consumer, Provider } = React.createContext()class Children extends React.Component { render() { return ({ (value) => ( ) }}class Parent extends React.Component { render() { return () }Children1
{value.text}
) }}export default Parent Parent
5.node的events模块的单例通信
function Children(props) { return ()}function Parent() { let [text, setText] = useState("这是爸爸传给你的东西") let event = new Events() event.on("foo", () => { setText("改变了") }) return (Children
{props.text}
)}export default ParentParent
注意⚠️:这种通信记住在顶部引入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) }}let mapStataToProps = (state) => { return { text: state.text }}export default connect(mapStataToProps, null)(Child){this.props.text}
Parent.js
class Parent extends React.Component { render() { return () }}export default Parent Parent
注意:记得安装redux和react-redux。
【相关推荐:Redis视频教程】
以上就是react通信有哪些方式的详细内容,更多请关注php中文网其它相关文章!