【问题标题】:Parent Component isn't passing prop to child Component父组件没有将道具传递给子组件
【发布时间】:2016-06-16 23:09:59
【问题描述】:

所以在我的父组件的渲染函数中我有:

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

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

【问题讨论】:

    标签: javascript reactjs components


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      使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
          />);
      }
      

      希望这能解决!

      【讨论】:

        猜你喜欢
        • 2019-11-12
        • 1970-01-01
        • 1970-01-01
        • 2020-09-01
        • 1970-01-01
        • 2021-07-04
        • 2020-11-23
        相关资源
        最近更新 更多