I'm just wondering what the best way is to complete this React task. Say, I have a component like this one:
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>
);
}
});
I need to be able to pass down proxyState(state)
to a great-grandchild component, where the child (and grandchild) will be rendered using ReactLayout
.
As an example, here's a bit of code from FlowRouter showing how I'm currently rendering the component(s) that are involved with this chain:
FlowRouter.route('/proxies', {
name: 'proxies',
action() {
const content = <ProxyPage />;
ReactLayout.render(App, {
title: 'Proxies',
layout: <MainLayout content={content} />
});
}
});
The content renders just fine, but what I don't understand how to do is pass proxyState()
down to <MainLayout />
(and subsequently, <ProxyPage />
that will be rendered inside it, and then <ProxyForm />
, which gets rendered inside that.
Any assistance would be greatly appreciated. I'm new to the concept of passing props around, and I guess this might be a semi-advanced thing for someone who has been writing React stuff for maybe 3 days now. Thanks in advance!
If anyone's needing to look at the rest of my code to get an idea of what I'm looking for, the project is (currently) in a public repository: https://bitbucket.org/czbaker/karuto
The simplest way to pass props to children is to literally directly pass them:
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} />
);
}
});
Assuming you have a tree family structure, you can just have the parents keep passing down the props you need them to pass down.
However, the above can get a bit tedious, especially if you want to send a prop to every layer in a deep tree. To make life simpler, React has a concept called context
s. These allow you to specify a prop to be available to all children of a parent prop, regardless of depth.
I'm not going to copy/paste the example from the docs, so go check it out here: https://facebook.github.io/react/docs/context.html and feel free to ask questions :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.