'Range' 输入类型不会在 React.js 文档上滑动,而是在代码笔上工作?



我正试图在React应用程序中实现一个范围滑块,但当我输入代码时,滑块根本不起作用?

它不会左右拖动。点击它也不会移动它。尽管,如果我在代码笔上使用完全相同的代码,滑块工作完全正常。

我试过对此进行研究,但找不到明确的答案。有人知道可能出了什么问题吗?

有问题的代码:

<input
type="range"
min="1"
max="100"
value="50"
class="slider"
id="myRange"
/>

这是我的整个应用程序。


import "./App.scss"
import React, { useState } from "react"
function App() {
const [firstColorInput, setFirstColorInput] = useState("")
const [secondColorInput, setSecondColorInput] = useState("")
const [mode, setMode] = useState("single")
const handlefirstColorChange = (e) => {
setFirstColorInput(e.target.value)
console.log(firstColorInput)
}
const handlesecondColorChange = (e) => {
setSecondColorInput(e.target.value)
console.log(secondColorInput)
}
return (
<div
className="App"
style={{
background:
mode === "single"
? firstColorInput
: `linear-gradient(${firstColorInput}, ${secondColorInput})`,
}}
>
<div class="container">
<div id="colour_picker">
<input
type="text"
onChange={handlefirstColorChange}
value={firstColorInput}
id="input_first"
placeholder={
mode === "single"
? "Enter color name or code"
: "Enter First Colour"
}
class="inputs"
/>
<input
type="text"
onChange={handlesecondColorChange}
value={secondColorInput}
style={{ display: mode === "single" ? "none" : "block" }}
id="input_second"
placeholder={mode === "single" ? "" : "Enter Second Colour"}
class="inputs"
/>
<button
onClick={() => setMode(mode === "single" ? "gradient" : "single")}
>
{mode === "single" ? "Single Colour" : "Gradient"}
</button>
<input
type="range"
min="1"
max="100"
value="50"
class="slider"
id="myRange"
/>
</div>
</div>
</div>
)
}
export default App
value="50"

在react中,这告诉它将值设置为50,并且永远不要更改它

您有两个选项:您可以将输入作为不受控制的组件运行,方法是给它一个默认值:

defaultValue="50"

或者你可以把它作为一个受控组件,通过一个状态变量:

const [value, setValue] = useState("50");
//...
<input
type="range"
min="1"
max="100"
value={value}
onChange={(e) => setValue(e.target.value)}
class="slider"
id="myRange"
/>

如果你不确定你需要哪一个,那就做受控版本。有关受控和非受控组件之间差异的更多信息,请参阅本页和本页

最新更新