laravel blade 组件视图中的变量未定义错误

Variable undefined error in laravel blade component view

组件InputError.php

<?php

namespace App\View\Components;

use Illuminate\View\Component;

class InputError extends Component
{
    /**
     * Create a new component instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\Contracts\View\View|\Closure|string
     */
    public function render()
    {
        return view('components.input-error');
    }
}

Blade input-error.blade.php

@props(['for'])

@error($for)
    <label {!! $attributes->merge(['class' => 'error']) !!}>
        {{ $message }}
    </label>
@enderror

Blade 查看

<x-input-error for="title" />

错误

Undefined variable: for

我不想更改原始 jetstream 组件,我该如何修复它?

来自文档:

You should define the component's required data in its class constructor. All public properties on a component will automatically be made available to the component's view. It is not necessary to pass the data to the view from the component's render method: (...)

因此,在您的情况下:

class InputError extends Component
{
    public $for;

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

    public function render()
    {
        return view('components.input-error');
    }
}

那么你应该可以传递数据了:

<x-input-error for="my-title" />

PS:我认为问题出在 @prop 指令的使用上。该指令用于没有链接到视图的专用组件 class 的匿名组件。我几乎总是使用匿名组件,所以我不能完全确定这种行为。

PS2:在您的 <label> 标签中使用 {{ }} 而不是 {!! !!}

input.php

class Input extends Component
{
    /**
     * Create a new component instance.
     *
     * @return void
     */
    public $type;
    public $inputclass;
    public function __construct($inputclass=null,$color='primary')
    {
        $this->inputclass = $inputclass ?? "w-full px-4 py-2 border rounded-md dark:bg-darker dark:border-gray-700 focus:outline-none focus:ring focus:ring-$color-100 dark:focus:ring-$color-darker";
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\Contracts\View\View|\Closure|string
     */
    public function render()
    {
        return view('components.input');
    }
}

input.blade.php

@props(['class'=>'','name'=>''])
<input 
    {{ $attributes->merge(['class' => $inputclass.' '.$class]) }}
/>
@error($name)
<span class="mt-2 text-sm text-red-600">{{ $message }}</span>
@enderror

使用组件

<x-input
   color="secondary"
   wire:model.lazy="email"
   type="email"
   name="email"
   placeholder="Email address"
   equired
/>