Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

javascript - 从另一个组件获取参数[React JS](Get arguments from another component [React JS])

I'm creating a web-app using React.

(我正在使用React创建一个Web应用程序。)

I'm facing a problem with my navbar and the main content:

(我的导航栏和主要内容遇到了问题:)

In AppWrapper I have this:

(在AppWrapper中,我有以下内容:)

var contents = [
   <Offers />,
   <Create />,
   <List />
];

and where each item will be the content displaying.

(以及每个项目将显示内容的位置。)

In getInitialState I initialize it like this:

(在getInitialState中,我将其初始化为:)

getInitialState: function() {
  return {
    currentTab: 0
  };
},

Later, in render function I have this:

(后来,在渲染函数中我有这个:)

return (
  <div>
    <Navbar />
    <div className='mainPanel'>
      {contents[this.state.currentTab]}
    </div>
  </div>
);

You can see that I call the navbar component before the content.

(您可以看到,我在内容之前调用了导航栏组件。)

In Navbar component I have a menu where, from there, I want to change the currentTab of AppWrapper .

(在Navbar组件中,我有一个菜单,从那里,我想更改AppWrapper的currentTab。)

How can I do that?

(我怎样才能做到这一点?)

Thank you for advance!

(谢谢你的进步!)

  ask by Albert Olivé translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

After trying to handle it, I found how to do that.

(尝试处理之后,我找到了解决方法。)

This is the answer:

(这是答案:)

<Navbar selectTab={this.selectTab} />

selectTab: function(tab) {
    this.setState({ currentTab: tab });
}

I pass to Navbar component the function "selectTab of the parent ( AppWrapper ).

(我将Navbar组件的功能“父( appWrapper )的selectTab ”传递给了Navbar组件。)

Then in Navbar component:

(然后在Navbar组件中:)

<li>
    <a onClick={this.selectTab.bind(this, 0)}><i className="fa fa-dashboard fa-fw" /> Dashboard</a>
</li>
<li>
   <a onClick={this.selectTab.bind(this, 1)}><i className="fa fa-edit fa-fw" /> Create</a>
</li>

Then in selectTab of Navbar I change the props to current tab.

(然后在Navbar的 selectTab中,将props更改为current选项卡。)

selectTab: function(tab) {
    this.props.selectTab(tab);
},

Hope someone helps this answer!

(希望有人帮助这个答案!)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...