【问题标题】:Which is the parent component in this reactJS code?这个 reactJS 代码中的父组件是哪个?
【发布时间】:2018-03-02 02:28:20
【问题描述】:

这是我第一次在这里发帖,希望能从你们和其他人那里学到更多!

下面是我练习 ReactJS 的代码。我正在从 Chinnathambi 的书中学习如何编程。我有一个问题,因为这本书没有指定哪个是父组件。

    var Army = React.createClass ({
    render: function () {
      return (
        <div>
          <p>{this.props.insignia}</p>
          <p>{this.props.color}</p>
          <p>{this.props.country}</p>
        </div>
        );
      }
    });
/*In this example we use the spread operator to pass an array of our values to
our component. ...this.props poses the same values as insignia, color and country*/
var Unit = React.createClass ({
    render: function () {
      return (
        <div>
          <Army {...this.props}/>
        </div>
        );
      }
    });

var Uniform = React.createClass ({
    render: function () {
      return (
        <div>
          <Unit {...this.props}/>
        </div>
        );
      }
    });

/*This is an example of JSX: 
  Our component has been declared inside of the variable uniformComponent and
  it has been implemented in our DOM render method by encapsulating them in 
  curly braces.
*/
var uniformComponent = <Uniform insignia="US ARMY" color="OCP" country="USA"/>;
var placement = document.querySelector("#container3");
ReactDOM.render (
  <div>
  {uniformComponent}
  </div>,
  placement
  );

这是一个简单的代码,其中属性从 Uniform>Unit>Army 传递。哪个是父组件?老实说,我认为它是 Uniform 组件,因为在我们挂载组件时所有的属性值都会被声明。这对我来说有点令人困惑,因为我知道父组件可以将属性传递给子组件,但子组件不能传递属性。在我正在阅读的书中,示例来自衬衫>标签>显示。

我真的只需要澄清这三个组件中的哪个是实际的父组件。是声明属性的地方还是初始化属性值的地方?

【问题讨论】:

    标签: javascript reactjs redux jsx babeljs


    【解决方案1】:

    如你所说,

    • UniformUnit 的父级
    • UnitArmy 的父级

    基本上父组件渲染子组件,所以如果你在渲染中看到一个组件,那么它就是一个子组件。

    --

    此外,有时您会听到“祖父”表示多个级别的父级,或“根”组件表示位于树最顶端的那个。

    【讨论】:

    • 所以它是 prop 值被初始化的地方!谢谢!
    【解决方案2】:

    你是对的。 &lt;Uniform /&gt; 是父组件。当它安装在 DOM 中时,它的外观是这样的:

    <Uniform>
      <Unit>
        <Army />
      <Unit />
    <Uniform />
    

    这让我有点困惑,因为我知道父组件可以将属性传递给子组件,但子组件不能传递属性。

    嗯,子组件也可以通过向父组件附加回调来传递值。详细答案请查看Pass props to parent component in React.js

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多