问问题
96 次
3 回答
0
我同意这很烦人,选择框的工作方式就像默认值始终为空 "" 并且您希望您的用户选择一个值。
但是如果我必须这样做,我认为最干净的方法是使用 ReactuseState
并封装组件。
import React from "react";
import "./styles.css";
import { useState } from "react";
export default function App() {
const [selection, setSelection] = useState("React"); // set default value here
const handleSelection = (e) => {
const selectionValue = e.target.value
console.log(selectionValue);
setSelection(selectionValue); // set current state
};
return (
<div className="App">
{/* show current state in below div */}
<h1>Selected Topic: {selection}</h1>
<select onChange={handleSelection} defaultValue="React">
<option value="React">React</option>
<option value="Vue">Vue</option>
<option value="Angular">Angular</option>
</select>
</div>
);
}
于 2020-08-06T16:24:50.213 回答
0
我认为这是正常行为,因为您将默认值设置为空,但您没有指定<option value="" />
具有空值的标签,这意味着浏览器将选择第一项作为选定项目。为了更有意义,您应该添加尚未选择的空选项:
<option value="react">React</option>
<option value="vue">Vue</option>
<option value="angular">Angular</option>
<option value="">---</option>
---
然后浏览器将默认选择空选项。
于 2020-08-06T15:44:15.990 回答
0
更改this.state = { topic: '' }
为,this.state = { topic: 'react' }
因此整个代码应为:
import React, { Component } from 'react'
class Form extends Component {
constructor(props) {
super(props)
this.state = {
topic: 'react',
}
}
handleTopicChange = event => {
this.setState({topic: event.target.value,})}
handleSubmit = event => {
alert(`${this.state.topic}`)
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div>
<label>Topic</label>
<select value={this.state.topic} onChange={this.handleTopicChange}>
<option value="react">React</option>
<option value="vue">Vue</option>
<option value="angular">Angular</option>
</select>
</div>
<button type="submit">Submit</button>
</form>
)
}}
export default Form
于 2020-08-06T16:06:14.880 回答