javascript - 学习react + es6 关于props及其传递的问题
大家讲道理
大家讲道理 2017-04-10 18:09:04
[JavaScript讨论组]

我的父组件代码

import React from 'react';
import ComponentChild from './component-child.jsx';

export default class Hello extends React.Component {
     render() {
        return  <p>
                    <h1>Hello world</h1>
                    <ComponentChild data={this.props.jsonArray} />
                </p>;
      }
}
Hello.defaultProps = {
    jsonArray: [
            {
                id: 3,
                val: "test3"
            },
            {
                id: 4,
                val: "test4"
            }
        ]
};   

我的子组件代码

import React from 'react';

//item
export default class ComponentChildList extends React.Component {
    render() {
        return <li>{this.props.jsonArrayTest.val}</li>;
    }
}

export default class ComponentChild extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            example: 'example',
        };
    }
    render() {
        return  <p>
                    <ul>
                        {
                            this.props.jsonArrayTest.map(function(item){
                                return <ComponentChildList key={item.id} data={item} />
                            })
                        }
                    </ul>
                </p>;
    }
}
ComponentChild.defaultProps = {
    jsonArrayTest: [
            {
                id: 1,
                val: "test1"
            },
            {
                id: 2,
                val: "test2"
            }
        ]
};     

问题:
1, 子组件报错Cannot read property 'val' of undefined
2, 父组件如何传递props覆盖子组件的默认值

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(2)
大家讲道理

1

export default class ComponentChildList extends React.Component {
    render() {
        return <li>{this.props.data.val}</li>;
    }
}

2

照传递过去就行,如果父组件有传递props给子组件则子组件会使用传递过来的props,否则就会使用默认的props,需要注意传递过去的props的格式(命名,键名)要和默认的一致,这样才会实现覆盖
迷茫

楼主试下这个

export default class ComponentChildList extends React.Component {
    render() {
        return <li>{this.props.data.val}</li>;
    }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号