我只是想知道完成此React任务的最佳方法是什么。 说,我有一个这样的组件:
App = React.createClass({
//mixins: [ReactMeteorData],
// Initial State declared here.
getInitialState() {
return {};
},
proxyState(state) {
console.log(`Triggered proxyState, top-level: ${state}`);
},
render() {
return (
<div>
{this.props.layout}
</div>
);
}
});
我需要能够将proxyState(state)
传递给一个曾孙子组件,子组件(和孙子组件)将使用ReactLayout
进行渲染。
作为一个例子,这里有一些来自FlowRouter的代码,展示了我目前如何呈现与该链相关的组件:
FlowRouter.route('/proxies', {
name: 'proxies',
action() {
const content = <ProxyPage />;
ReactLayout.render(App, {
title: 'Proxies',
layout: <MainLayout content={content} />
});
}
});
内容渲染得很好,但我不明白该怎么做的是将proxyState()
传递给<MainLayout />
(以及随后,<ProxyPage />
将会在其中呈现,然后<ProxyForm />
,在其中进行渲染。
非常感谢任何帮助。我对传递道具的概念不熟悉,我想对于那些现在已经写了3天的React东西的人来说,这可能是一个半高级的事情。提前谢谢!
如果有人需要查看我的其余代码以了解我正在寻找的内容,那么该项目(目前)位于公共存储库中:https://bitbucket.org/czbaker/karuto
答案 0 :(得分:2)
将道具传递给儿童的最简单方法是直接传递道具:
var Child = React.createClass({
render: function() {
return (
<div>{this.props.myProp}</div>
);
}
});
var Parent = React.createClass({
getDefaultProps: function() {
return (
someProp: "I'm a prop value!"
);
},
render: function() {
return (
<Child myProp={this.props.someProp} />
);
}
});
假设你有一个树家庭结构,你可以让父母继续传递你需要传递的道具。
但是,上面的内容会变得有点乏味,特别是如果你想向深树中的每一层发送一个道具。为了简化生活,React有一个名为context
s的概念。这些允许您指定父级道具的所有子项可用的道具,无论深度如何。
我不打算从文档中复制/粘贴示例,因此请在此处查看:https://facebook.github.io/react/docs/context.html并随时提出问题:)