Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/reporting-services/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 我怎样才能把道具传给孩子们?_Reactjs_React Router - Fatal编程技术网

Reactjs 我怎样才能把道具传给孩子们?

Reactjs 我怎样才能把道具传给孩子们?,reactjs,react-router,Reactjs,React Router,我查过了 到目前为止,我还不能理解处理程序部分。所以我希望有一个更简单的例子 以下是我的主要父组件: class appTemplate extends React.Component { render() { return ( <div> <Header lang={this.props.route.path}/> {this.props.children}

我查过了

到目前为止,我还不能理解
处理程序
部分。所以我希望有一个更简单的例子

以下是我的主要父组件:

class appTemplate extends React.Component {
    render() {
        return (
            <div>
                <Header lang={this.props.route.path}/>
                {this.props.children}
                <Footer lang={this.props.route.path}/>
            </div>
        );
    }
}
类appTemplate扩展React.Component{
render(){
返回(
{this.props.children}
);
}
}
我要做的是将prop
this.props.route.path传递给我的子组件,即
this.props.children

我并不是真的完全熟悉所有的术语,尽管过去几个月我已经接触过React了


请举一个有适当解释的例子,不胜感激。谢谢。

React具有克隆元素功能。其想法是克隆子对象,作为道具的一部分在路径上传递:

class appTemplate extends React.Component {
    render() {
        let children = null;
        if (this.props.children) {
          children = React.cloneElement(this.props.children, {
            path: this.props.route.path
          })
        }
        return (
            <div>
                <Header lang={this.props.route.path}/>
                {children}
                <Footer lang={this.props.route.path}/>
            </div>
        );
    }
}
类appTemplate扩展React.Component{
render(){
让children=null;
如果(本.道具.儿童){
children=React.cloneElement(this.props.children{
路径:this.props.route.path
})
}
返回(
{儿童}
);
}
}
然后,您应该能够在子元素中使用
this.props.path
访问路径,但(据我记忆)不能从嵌套在子元素中的元素中访问路径

您可以在此处阅读有关克隆和传递值的更多信息:
实现这一目标的正确方法是使用

类appTemplate扩展React.Component{
render(){
返回(
{React.Children.map(
这个,道具,孩子们,
child=>React.cloneElement(child,
{ 
自定义道具:“这是你的道具”,
路径:this.props.route.path
})
)}
);
}
}

这个例子非常古老,请查看最新的文档。。。。如果您使用redux而不仅仅是使用连接包装器,这将使您能够访问应用程序中的任何位置和路由
class appTemplate extends React.Component {
    render() {
        return (
            <div>
                <Header lang={this.props.route.path}/>
                {React.Children.map(
                       this.props.children,
                       child => React.cloneElement(child,
                                   { 
                                      customProp: "Here is your prop",
                                      path: this.props.route.path
                                   })
                )}
                <Footer lang={this.props.route.path}/>
            </div>
        );
    }
}