【问题标题】:React16 Two components communicatingReact16 两个组件通信
【发布时间】:2019-01-08 11:19:32
【问题描述】:

ReactJS 两个组件通信,在角度上,我们只是使用服务最佳方式,但这里我是 react 16 的新手。

【问题讨论】:

  • 取决于组件在树中相互关联的位置:(1) 向下传递 props,(2) 使用 Context API (3) 使用 redux 或 mobx 等共享存储解决方案
  • 我想分享我的所有组件的登录详细信息,在 angular7 中,我们在这里有最好的服务方式,哪一种是反应 16 的最佳方式。请提前帮助我
  • 我们只是在使用服务——这只是其中一种方式。另一种方式是通过共同的父母进行交流。这就是你通常在 React 中使用的方式。另一种是通过全局状态进行通信 - Redux 或上下文 API。
  • React 只是视图层,由您决定。最流行的解决方案是redux + react-redux 包,很多教程都在这方面,初学者设置和习惯有点棘手。否则mobx + mobx-react 可能是第二受欢迎的,它使用可观察对象,因此可能更接近 Angular 范例。
  • 非常感谢您的澄清

标签: reactjs react-16


【解决方案1】:

react 中的两个组件可以通过以下方式进行通信

父组件->子组件通过道具

子 -> 父通过回调

Child -> Child 通过使用他们的 closet 父组件

例如:

import React, {Component} from 'react';
class Parent extends Component {
    constructor() {
      super()
      this.state = {
       name: "John Doe"
      }
      this.changeName = this.changeName.bind(this)
    }
   changeName(newName) {
     this.setState({
       name: newName
     })
   }

    render() {
       return (
           <div>
               // passing data from parent component to child component using props
               // name={this.state.name} changeName={this.changeName}
               <Child name={this.state.name} changeName={this.changeName} />
               <SecondChild name={this.state.name} />
           </div>
         )

      }
 }

 function Child(props) {
   return (
      <div>
         <h1>My name in Child Component is: {props.name} </h1>
         // passing data from child component to parent component using Callback
         // onClick={() => props.changeName('Jeremy Smith')}
         <button onClick={() => props.changeName('Jeremy Smith')}>Change Name</button>
         // when button is clicked "Jeremy Smith" is passed to parent component and 
         // from their passed to both Child and SecondChild components
         // this way we communicate between two child components
      </div>
    )
 }

 function SecondChild(props) {
   return <h1>My Name in Second Child Component is: {props.name}</h1> 
 }

另外

您还可以使用 React Context API 将数据向下传递给子组件。

或者使用像 redux 这样的状态管理库来创建单个共享存储并将所需的数据传递给组件。

【讨论】:

  • 这是我的荣幸
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-23
  • 2020-08-03
  • 1970-01-01
  • 2017-04-30
  • 2018-02-08
相关资源
最近更新 更多