簡體   English   中英

laravel 刀片組件視圖中的變量未定義錯誤

[英]Variable undefined error in laravel blade component view

組件輸入錯誤.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.php

@props(['for'])

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

葉片視圖

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

錯誤

未定義的變量:對於

我不想更改原始的 Jetstream 組件,我該如何修復它?

從文檔:

您應該在其 class 構造函數中定義組件所需的數據。 組件上的所有公共屬性將自動提供給組件的視圖。 沒有必要將數據從組件的渲染方法傳遞到視圖:(...)

所以,在你的情況下:

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>標簽中使用{{ }}而不是{!! !!} {!! !!}

輸入.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');
    }
}

輸入.刀片.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
/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM