简体   繁体   English

React.js 将数据从类组件传递到 ReactDOM.render 中的另一个组件

[英]React.js passing data from class component to another in ReactDOM.render

I have this problem where I want to update my component FooBar if Foo's state changes.我有这个问题,如果 Foo 的状态发生变化,我想更新我的组件 FooBar。 How can I do it?我该怎么做? This doesn't work.这不起作用。

import React from "react"
import ReactDOM from "react-dom"
import FooBar from "./FooBar"

class Foo extends React.Component {
    constructor() {
       super()
       this.state = { data: [] } 
   } 

   changeData() {
       someCode
   }

   render() {
       return (
           some html
       )
   }
}

ReactDom.render(<Foo />, document.getElementById('Something'))
ReactDom.render(<FooBar data={this.state.data}/>, document.getElementById('SomethingElse'))

Question is a bit confusing, You can try this if it works问题有点混乱,你可以试试这个,如果它有效

 changeData = () =>
       this.setState({data:'your changes'})
   }

the above code will update the state, thus rest of component connected with class will render automatic.上面的代码将更新状态,因此与类连接的其余组件将自动呈现。

Create a parent component, render both foo and foobar inside.创建一个父组件,在里面渲染 foo 和 foobar。 now you can use state normally for communication between them and only have to use one ReactDom.Render现在你可以正常使用 state 进行它们之间的通信,并且只需要使用一个 ReactDom.Render

class Parent extends React.Component{
   render(){
      return(
        <div>
           <Foo/>
           <Foobar/>
       </div>
      );
   }
}


ReactDom.render(<Parent  />, document.getElementById('Something'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM