设置新状态可以改变数据的颜色属性,但不能改变图像
Setting new state can change the data's color attribute, but not image
我想制作一个小应用程序,用户可以在其中选择car/motocycle他们喜欢的颜色。
我快要实现它了,但不幸的是,当我单击颜色按钮时,它只会更改颜色的书面名称,但不会更改 car/motocycle 在该特定所选颜色中的预览图像.
我用的是同样的逻辑,所以我不知道为什么它在一部分起作用,而另一部分不起作用。
当前行为示例:
选择汽车 1 的红色 -> 默认颜色名称将被覆盖,但图像将丢失,而不是将其更改为红色汽车的正确图像。
我创建了当前行为的沙箱:
https://codesandbox.io/s/festive-framework-9u75w?file=/src/App.js
我稍微改变了你的沙箱
我试图在 colors
对象中找到图像。这意味着 car/motorcycle 的 image
属性 不再需要了。
<CarInfo
key={item.id}
image={
item.car.colors[item.car["selected"].toLowerCase()]
? item.car.colors[
item.car["selected"].toLowerCase()
].image
: null
}
name={item.car.name}
color={item.car["selected"]}
/>
和
<MotocycleInfo
key={item.id}
image={
item.motocycle.colors[
item.motocycle["selected"].toLowerCase()
]
? item.motocycle.colors[
item.motocycle["selected"].toLowerCase()
].image
: null
}
name={item.motocycle.name}
color={item.motocycle["selected"]}
/>
代码可以缩短,例如您需要默认显示第一张图片,所以
image={
item.car.colors[
item.car["selected"]
? item.car["selected"].toLowerCase()
: 0
].image
}
只需在 handleColorCar() 方法中替换下面的单行。
// Your code
changedItem.motocycle.image = e.target.value;
// Working code
changedItem.car.image = selectedData.car.colors[e.target.value.toLowerCase()].image;
我想制作一个小应用程序,用户可以在其中选择car/motocycle他们喜欢的颜色。
我快要实现它了,但不幸的是,当我单击颜色按钮时,它只会更改颜色的书面名称,但不会更改 car/motocycle 在该特定所选颜色中的预览图像.
我用的是同样的逻辑,所以我不知道为什么它在一部分起作用,而另一部分不起作用。
当前行为示例: 选择汽车 1 的红色 -> 默认颜色名称将被覆盖,但图像将丢失,而不是将其更改为红色汽车的正确图像。
我创建了当前行为的沙箱:
https://codesandbox.io/s/festive-framework-9u75w?file=/src/App.js
我稍微改变了你的沙箱
我试图在 colors
对象中找到图像。这意味着 car/motorcycle 的 image
属性 不再需要了。
<CarInfo
key={item.id}
image={
item.car.colors[item.car["selected"].toLowerCase()]
? item.car.colors[
item.car["selected"].toLowerCase()
].image
: null
}
name={item.car.name}
color={item.car["selected"]}
/>
和
<MotocycleInfo
key={item.id}
image={
item.motocycle.colors[
item.motocycle["selected"].toLowerCase()
]
? item.motocycle.colors[
item.motocycle["selected"].toLowerCase()
].image
: null
}
name={item.motocycle.name}
color={item.motocycle["selected"]}
/>
代码可以缩短,例如您需要默认显示第一张图片,所以
image={
item.car.colors[
item.car["selected"]
? item.car["selected"].toLowerCase()
: 0
].image
}
只需在 handleColorCar() 方法中替换下面的单行。
// Your code
changedItem.motocycle.image = e.target.value;
// Working code
changedItem.car.image = selectedData.car.colors[e.target.value.toLowerCase()].image;