ReactJs从组件到组件传递参数

时间:2016-07-25 12:47:15

标签: reactjs

我还在学习ReactJs,我偶然发现了一个问题。我已将Header Content和Footer呈现为不同的组件。当用户登录ContentDidMount of Content时,我会得到Json的姓名,姓氏等。当我收到数据时,我想将用户名添加到标题,如Welcome,username。但我不知道如何传递那个或哪里,以便组件Header得到名称。

索引

render: function() {

if(this.state.signup == true) {
  return  (
    <div>
    <Header data = {this.state.signup} logout={this.logOut}/>
    <MenuBar/>
      <Content/>
     <Footer/>
    </div>
  );
} else {
  return  (
    <div>
     <Header data = {this.state.signup}/>
    <MenuBar/>
      <Login func={this.logIn}/>
      <Footer/>
    </div>
  );
}
},

因此,如果用户已登录,则状态更改为true。这打开了内容。 在这里我得到userdata

内容

componentDidMount: function() {
document.title = "Dashboard";
this.getUser();

 },

 getUser: function(){
 $.getJSON(url, this.handleData);
},

handleData: function(data){
 this.setState({data: data});
 },

现在当发生这种情况时,我想用Json中的Welcome,Name of the user更改标题。

标题

render() {
if(this.props.data) //Check if user is logged in
{
  return (
  <section className="heading">
            <div className="user-message">Welcome, User</div> //Here i would like to change user name from Json         
  </section> 
);

 }
else{
  return (
        <section className="heading">
            <div className="user-message">You are not connected</div>
        </section>
  );

我不知道我是否完全了解ReactJs所以我可能会走错方向。

那我该如何更改名称?我想过将Header移动到内容并从那里传递,但是有更好的方法吗?

2 个答案:

答案 0 :(得分:4)

我会建议创建一个名为UserMessage的新组件

,而不是if else中的return语句
class UserMessage extends Component{
  render(){
     return <div className="user-message">{this.props.message}</div>
   }
}

在标题中,

{
this.props.data?<UserMessage message={this.props.data.message}/>:<UserMessage message="You are not connected"/>
}

我在类似的用例中使用过这种情况,当数据不可用时我必须显示loadingBar。

由于

答案 1 :(得分:-1)

您可以做的是在componentDidMount上为每个组件注册一个调度程序,当您的用户登录时,您的userStore应该发出一个事件,而您的组件只需更新状态就可以记录用户。

相关问题