ReactJS - 孩子如何访问它的父母的道具?

时间:2016-11-04 08:35:13

标签: javascript reactjs ecmascript-6

孩子如何访问其父母的道具?例如,

父组件 - footer.jsx:

import React from 'react';
import $ from 'jquery';

import NavItem from './nav-item';

class Footer extends React.Component
{
    constructor(props) {
        super(props);
        this.state = {
            publicUrl: null,
            currentUrl: null,
            navitems: [],
        };
    }

    // Then fetch the data using $.getJSON():
    componentDidMount() {
        this.serverRequest = $.getJSON(this.props.source, function (result) {
            this.setState({
                currentUrl: window.location.href,
                publicUrl: result.publicUrl,
                navitems: result.nav
            });
        }.bind(this));
    }

    componentWillUnmount() {
        this.serverRequest.abort();
    }

    render() {
        var loop = this.state.navitems.map(function(item, index){
            return <NavItem key={index} item={item}></NavItem>;
        });

        return (
            <div>
                <div className="nav">
                    <ul>{ loop }</ul>
                    <p>{this.state.publicUrl}</p>
                    <p>{this.state.currentUrl}</p>
                </div>
            </div>
        )
    }
}

export { Footer as default }

子组件 - nav-item.jsx:

导入来自&#39;反应&#39 ;;

的反应
class NavItem extends React.Component
{
    constructor(props) {
        super(props);
    }

    render() {
        return <li><a href={this.props.publicUrl + '/' + this.props.item.url}>{this.props.item.title}</a></li>
    }
}

export { NavItem as default }

结果为footer.jsx(父级):

this.props.publicUrl // http://my-website.com

结果为nav-item.jsx(孩子):

this.props.publicUrl // undefined but it should be http://my-website.com

有什么想法吗?

示例数据:

{
    "publicUrl": "http:\/\/my-website.com",
    "nav": [{
        "navId": "3",
        "title": "Home
        "code": "home
        "href": null,
        "style": null,
        "sort": "3",
        "url": "home
        "parentId": null,
        "totalChildren": "0",
        "createdOn": null,
        "updatedOn": null
    }, {
        "navId": "4",
        "title": "About
        "code": "about
        "href": null,
        "style": null,
        "sort": "4",
        "url": "about
        "parentId": null,
        "totalChildren": "0",
        "createdOn": null,
        "updatedOn": null
    }, {
        "navId": "5",
        "title": "Contact",
        "code": "contact",
        "href": "#contact",
        "style": null,
        "sort": "5",
        "url": "contact",
        "parentId": null,
        "totalChildren": "0",
        "createdOn": null,
        "updatedOn": null
    }]
}

5 个答案:

答案 0 :(得分:3)

无法访问子组件中的父道具。你可以通过以下两种方式实现这一目标: -

  1. 通过这样的道具将值传递给来自父级的子组件: - $productCodes
  2. 将状态值和调度操作中的值设置为从状态获取值。
  3. 另外,我注意到您在 componentDidMount 中设置了状态值,因此要么在构造函数中设置state的默认值,要么在子组件中检查未定义的值

答案 1 :(得分:2)

点击这里

http://jsfiddle.net/z5m56sqn/

也可以使用this.handleChildClick.bind(null,childIndex) and then use this.state.childrenData[childIndex]

请注意,我们使用null上下文绑定,否则React会发出与其自动绑定系统相关的警告。使用null意味着您不想更改函数上下文。另见。

答案 2 :(得分:2)

我必须将this绑定到循环:

var loop = this.state.navitems.map(function(item, index){
            return <NavItem key={index} publicUrl={this.state.publicUrl} item={item}></NavItem>;
}.bind(this));

答案 3 :(得分:0)

您必须将prop的值从父级传递给子级。否则,这是不可能的。

您在上面的代码中所要做的就是这个小修改:

var loop = this.state.navitems.map(function(item, index){
   return <NavItem key={index} publicUrl={this.props.publicUrl} item={item}></NavItem>;
});

现在,NavItem将拥有等于父级publicUrl道具的道具publicUrl。所以基本上:

结果是footer.jsx(父级):

this.props.publicUrl // http://my-website.com

导致nav-item.jsx(child):

this.props.publicUrl // http://my-website.com

或者,虽然在您的情况下不推荐,但您可以将NavItem函数作为道具传递。该函数可以在父级中定义,并返回prop(或state或该组件的本地任何值)。

例如在您的父母中:

_getPublicUrl = () => {
  return this.props.publicUrl; //or any kind of value, local or otherwise
}
......
var loop = this.state.navitems.map(function(item, index){
   return <NavItem key={index} getPublicUrl={this._getPublicUrl} item={item}></NavItem>;
});

然后,在NavItem中,您可以调用此函数:

var parentPublicUrl = this.props.getPublicUrl();

同样,在这种特殊情况下不推荐。但是,它是获取state值的有用方法,或者是通过某些Ajax调用获取的变量。

答案 4 :(得分:0)

对此的另一种解决方法是

<MyChildComponent {...this} />

这会将所有父项道具传递给孩子,也可以将特定道具传递给

<MyChildComponent {...this.specificProps} />

希望这会有所帮助。