父组件未将prop传递给子组件

时间:2016-06-16 23:09:59

标签: javascript reactjs components

所以在我的父组件的渲染功能中,我有:

const BasicDetails = React.createClass({
    propTypes: {
        showFxMargin: bool
    },

    getDefaultProps() {
        return {
            showFxMargin: false
        };
    },
    render() {
        return(
        // other stuff...
        console.log('inside BasicDetails.jsx showFxMargin = ' + showFxMargin);
        <FxMargin
            showFxMargin={showFxMargin}
        />);
    }
 });

并且在子组件中我有:

import _ from 'lodash';
import React from 'react';

const FxMargin = React.createClass({
    render() {
        const {
            showFxMargin
        } = this.props;
        console.log('inside FxMargin.jsx showFxMargin = ' + showFxMargin);
        return showFxMargin ? (
            <div>
                <h1>FX Margin Baby</h1>
            </div>
        ) : (
            <p></p>
        );
    }
});

export default FxMargin;

在我的控制台中我得到了:

inside BasicDetails.jsx showFxMargin = true 

和     在BasicDetails.jsx中showFxMargin = false

但我永远不会得到:

inside FxMargin.jsx showFxMargin = true

我如何错误地传递道具?我没有收到任何错误

2 个答案:

答案 0 :(得分:0)

console.log组件内的{{1}}函数在返回内包含{{1}}语句。如果这是您尝试使用的确切代码,那么这就是您的组件无法正确呈现的原因。

删除该行后,您的代码就可以正常运行:http://jsbin.com/jozewoxubu/edit?js,output

答案 1 :(得分:0)

BasicDetails组件的render方法设为 -

render() {
    const {showFxMargin} = this.props; //change
    console.log('inside BasicDetails.jsx showFxMargin = ' + showFxMargin);
    return(
    // other stuff...

    <FxMargin
        showFxMargin={showFxMargin}
    />);
}

或 -

render() {
    console.log('inside BasicDetails.jsx showFxMargin = ' + this.props.showFxMargin); //change
    return(
    // other stuff...

    <FxMargin
        showFxMargin={this.props.showFxMargin} //change
    />);
}

希望这解决了!