0

您可以对一个 Blade X 组件进行多个实例化吗?

// app/view/components/foo.php

class Foo extends Component {
    public $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    ...
// resources/views/components/foo.blade.php
<div>
    {{  $name }}
</div>
// resources/views/rootcomponent.blade.php
<x-foo name="John"></x-foo>
<x-foo name="Mary"></x-foo>

它说: 无法声明类 App\View\Components\Foo,因为该名称已在使用中

如果您使用它一次 - 或者在没有构造函数/类变量的情况下使用它,它就可以工作。也许我会选择匿名方式,我只是好奇我做错了什么。

4

1 回答 1

0

似乎基类已经具有该属性,因此不需要重新声明。

// app/view/components/foo.php

class Foo extends Component {

    /* doesn't need to redeclare base class property */
    //public $name;

    public function __construct($name)
    {
        parent::__construct($name);

        /* doesn't need this line anymore. */
        // $this->name = $name;

        /* < Custom command line here.
             ... >

             But if there is no custom command line needed,
             then this constructor is useless,
             so no need to declare this.
          */
    }

    ...

希望这可以帮助任何人。

于 2020-03-22T00:47:39.863 回答