英文:
How do I detect a change in a select element in React?
问题
我有一个包含select
下拉框的HTML表单,供用户选择颜色,我正在尝试检测何时选择了新颜色。我已经添加了onchange
属性,并附加了一个console.log()
函数,但当我选择新颜色时,控制台没有输出任何内容。
这是我的select
元素,它包含在表单的return
语句中:
<select id="color-selector"
name="colors"
onchange={() => console.log("颜色已更改")}>
<option value="red">红色</option>
<option value="green">绿色</option>
<option value="blue">蓝色</option>
<option value="yellow">黄色</option>
<option value="orange">橙色</option>
<option value="purple">紫色</option>
</select>
我看到这在纯JS中是可能的,来自这个问题,但是否有办法在React中使用HTML的onchange
属性来实现这一点?
英文:
I have an HTML form with a select
dropdown for users to select a color, and I'm trying to detect when a new color has been selected. I've added the onchange
attribute with a console.log()
function, but nothing is printed to console when I select a new color.
Here's my select
element which is contained in the return
statement for the form:
<select id="color-selector"
name="colors"
onchange={() => console.log("Color has changed")}>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
<option value="orange">Orange</option>
<option value="purple">Purple</option>
</select>
I've seen this is possible in vanilla JS from this question, but is there a way to do this by using the onchange
attribute in the HTML in React?
答案1
得分: 1
import React, {
FormEvent,
FormEventHandler,
SelectHTMLAttributes,
useState,
} from "react";
export default function Home() {
const [color, setColor] = useState("");
function colorChange(e) {
setColor(e.target.value);
console.log(e.target.value);
}
return (
<div>
<select name="color" id="color" value={color} onChange={colorChange}>
<option value="">选择选项</option>
<option value="red">红色</option>
<option value="blue">蓝色</option>
<option value="green">绿色</option>
</select>
</div>
);
}
英文:
import React, {
FormEvent,
FormEventHandler,
SelectHTMLAttributes,
useState,
} from "react";
export default function Home() {
const [color, setColor] = useState("");
function colorChange(e) {
setColor(e.target.value);
console.log(e.target.value);
}
return (
<div>
<select name="color" id="color" value={color} onChange={colorChange}>
<option value="">Select option</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
</select>
</div>
);
}
答案2
得分: 1
你拼错了 onChange
。在 Reactjs 中,所有的回调函数都是以驼峰命名法编写的。在简单的 HTML 中,属性名是 onchange
。
英文:
You've misspelled onChange
. All callbacks in Reactjs are written in camel-case. It's in simple HTML that the attribute is onchange
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论