簡體   English   中英

如何在 img 標簽中使用 key 屬性?

[英]How to use the key attribute do in an img tag?

我有這個代碼來制作要在屏幕上顯示的圖像數組。 但是,我不知道圖像數組中的關鍵屬性是什么意思。 理想情況下,我想在單擊其中一張圖像時更改圖像的 src。 如果我向圖像添加idclassName屬性,並使用document.getElementById查找它,我會收到此警告: Warning: Prop `%s` did not match. Server: %s Client: %s%s Warning: Prop `%s` did not match. Server: %s Client: %s%s當我呈現頁面時。 我正在為這個項目使用 react 和 razzle。 有人能告訴我如何做到這一點嗎?

var shuffle = require("shuffle-array"),
    animals = [
      "frog0",
      "frog1",
      // ...
      "seal1",
      "armadillo0",
      "armadillo1"
    ];

function whatami(img) {
  alert(img);
}
var images = shuffle(animals).map(image => {
  return (
    <img
      onClick={() => {
        whatami(image);
      }}
      key={image}
      src={"/animalgameback.jpg"}
    />
  );
});
const App = () => (
  <div>
    <h3>My razzle app</h3>
    <div>{images}</div>
  </div>
);

export default App;

你的方法有很多問題。 我強烈建議閱讀有關如何在 ReactJS 中編寫 Javascript 的官方 React 文檔。

讓我們介紹一些基礎知識。 首先,你真的不應該在 React 中使用document.getElementById (除非情況很糟糕並且你試圖破解第三方庫)。 在大多數情況下,您使用 prop ref來引用安裝在 DOM 中的 React 節點。 但是,這只是對那些學習者的一些建議,享受使用參考的樂趣,這樣您就知道如何使用它們以及它們的作用。 但。 我建議,如果您“需要”引用或“需要”在運行時直接與 React 組件對話,那么您可能做錯了什么。

現在,由於您正在嘗試根據用戶事件或交互來“更改”某些內容,因此這是狀態管理的完美用例。 由於此更新或更改,React 為每個組件提供了自封裝有狀態對象的能力,並使用這些狀態“觸發”或重新渲染組件中的事物。

什么是鑰匙? 它是一個唯一標識符,您可以在每個渲染的 JSX 組件上使用它,顯示虛擬 DOM 和真實 DOM,該組件旨在按原樣重新渲染,而不是卸載、更改和重新安裝。 一個鍵允許 React 跟蹤哪些組件是預期的,而不是重新生成或安裝的。 您總是將 JSX 元素的鍵編寫為唯一 id。 如果您使 2 個 id 相同(嘗試並查看 :)),您會注意到它們在屏幕上呈現為 1,並且一個替換了另一個。

下面是我如何寫的:我制作了一個圖像作為“查看器”來顯示點擊了哪個圖像,以及附加到圖像的點擊事件處理程序以更改狀態。 渲染函數檢測圖像源更改並重新渲染組件。 因此,接收、使用和呈現新源。

編碼

 import React, { Component } from 'react'; const ANIMAL_DATA = [ 'frog0','frog1','sheep0','sheep1','snail0','snail1','mouse0','mouse1','bat0','bat1','walrus0', 'walrus1','giraffe0','giraffe1','zebra0','zebra1','dog0','dog1','octopus0','octopus1','hippo0', 'hippo1','camel0','camel1','pig0','pig1','rhino0','rhino1','rooster0','rooster1','panda0','panda1', 'turtle0','turtle1','raccoon0','raccoon1','polarbear0','polarbear1','lion0','lion1','bison0', 'bison1','orca0','orca1','snake0','snake1','shark0','shark1','toucan0','toucan1','butterfly0', 'butterfly1','anteater0','anteater1','seal0','seal1','armadillo0','armadillo1' ] class App extends Component { constructor(props) { super(props); this.state = { imageSource: 'animalgameback', }; } render() { const { imageSource } = this.state; return ( <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}> <img style={{ width: 143, height: 'auto' }} source={require(`/${imageSource}.jpg`)} /> { this.renderAnimalImages() } </div> ); } renderAnimalImages() { let images = []; ANIMAL_DATA.forEach((animal, animalIndex) => { // Be careful when assigning "onclick" methods to images, // you are better off sticking with W3C rules on this. Use elements // meant for "clicking" or "being clicked", ie <a>, <button>, etc images.push( <img src={`/${animal}.jpg`} key={`anima_image_${animalIndex}`} onClick={this.__handleImageClick(animal)} /> ); }); return images; } __handleImageClick = animal => event => { this.setState({ imageSource: animal }); }; } export default App;

key屬性用作身份聲明。 它幫助渲染引擎決定應該重新渲染哪些元素。

它在文檔中得到了很好的解釋。

暫無
暫無

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

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