If I have nested react elements how do I pass values in the parent element to the child element, when the child element is not internal to the parent element.
React.render(
<MainLayout>
<IndexDashboard />
</MainLayout>,
document.body);
In this code I have some functions in the MainLayout element that I would like to be able to access in the IndexDashboard element. How do I pass those functions to the child element?
答案 0 :(得分:1)
you would typically not render children elements like that in a React.render
call, and instead move IndexDashboard
to the render of your MainLayout
component so you can pass it the props it needs.
Edited per your comment: In the case of dynamically rendering children, i'd recommend passing it in as a prop based on what page youre on. I dont know if JSX supports that syntax, but you can use React.createElement
for sure.
React.render(
<MainLayout childProp={ IndexDashboard }/>,
document.body);
#MainLayout
render: function(){ (
return (
React.createElement(this.props.childProp, [otherProps...])
)
}
I'm not sure what you mean by 'its not internal to the Parent' since it clear is being rendered with it. If you absolutely cannot move the child to the parent render function, you would want to use a flux-like architecture using a store to house the data that both MainLayout
and IndexDashboard
require
答案 1 :(得分:1)
You can use the cloneElement function to modify the props of the child components:
#MainLayout
render: function(){ (
var contents = React.Children.map(this.props.children, function(child) {
return React.cloneElement(child, {onSomeEvent: this.onSomeChildEvent})
}.bind(this));
return (
<div>
{contents}
</div>
);
}
Refer to the following link for details: https://facebook.github.io/react/blog/2015/03/03/react-v0.13-rc2.html