如何在img标记中使用key属性do



我有这个代码来制作一个图像数组,显示在屏幕上。但是,我不知道图像数组中的关键属性是什么意思。理想情况下,每当单击其中一个图像时,我都希望更改图像的src。如果我在图像中添加idclassName属性,并使用document.getElementById进行查找,则在渲染页面时会收到以下警告: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(除非情况很糟糕,你正试图破解第三方库(。在大多数情况下,您使用道具ref来引用安装在DOM中的React节点。但是,只是给那些学习的人一些建议,用参考资料来获得乐趣,这样你就知道如何使用它们以及它们的作用。我建议,如果您"需要"引用或"需要"在运行时直接与React组件对话,那么您可能做错了什么。

现在,由于您正试图根据用户事件或交互来"更改"某些内容,因此这是状态管理的完美用例。React为每个组件提供了自封装有状态对象的能力,并使用这些状态来"触发"或重新呈现组件中的内容,这是由于这次更新或更改。

什么是钥匙?它是一个唯一的标识符,可以在每个呈现的JSX组件上使用,该组件显示虚拟DOM和真实DOM,该组件旨在按原样重新呈现,而不是卸载、更改和重新装载。一把钥匙可以让React跟踪哪些组件是预定的,而不是重新组装或安装的。你总是把JSX元素的一个键写为一个唯一的id。如果你让2个id相同(试试看:((,你会注意到它们在屏幕上呈现为1,一个替换另一个。

以下是我的写作方式:我制作了一个单独的图像作为"查看器"来显示单击了哪个图像,并在图像上附加了一个单击事件处理程序来更改状态。render函数检测图像源的更改并重新渲染组件。因此,新的源被接收、使用和呈现。

代码

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", i.e. <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属性用作身份声明。它有助于渲染引擎决定哪些元素应该重新渲染。

文档中对此进行了很好的解释。

最新更新