我有一个下拉列表,我用它来允许用户建立到后端的查询参数。
然后用户将单击一个按钮,我将访问用户在下拉菜单中设置的值,以调用后端端点。
现在我在访问所选值时遇到了很多麻烦。这是我的下拉菜单:
<div className="wrappers">
<div className="timeFrameLabel label">Time Frame: </div>
<select ref="timeFrame" className="timeFrameDropdown dropdown">
<option>1m</option>
<option>5m</option>
<option>15m</option>
<option>30m</option>
<option>1h</option>
<option>4h</option>
<option>1d</option>
</select>
</div>
按钮看起来像这样:
<Button className="goButton" onClick={this.getBacktestData}>
Get Data
</Button>
最后的onClick方法如下:
getBacktestData = async() => {
const {
symbol,
binSize,
startTime,
endTime,
} = this.state;
var quantity = document.querySelector(".quantityDropdown select")[document.querySelector(".quantityDropdown select").selectedIndex].innerHTML;
console.log(this.refs.asset.select)
console.log(this.refs.timeFrame)
console.log(this.refs.amount)
return await fetch("http://localhost:3001/backtest/getdata", {
method: 'POST',
body: JSON.stringify({symbol:symbol, binSize: binSize, startTime:startTime, endTime:endTime}), // data can be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(response => console.log(response))
.catch(error => console.error('Error:', error))
}
期望的结果是能够访问和 console.log() 选定的下拉元素。
我们非常欢迎任何帮助或提示。
最佳答案
这是访问 select
值的惯用方法,而无需处理 DOM。
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { selected: null };
}
handleChange = e => {
this.setState({ selected: e.target.value });
};
getBacktestData = async () => {
const { selected } = this.state;
// Do something with the selected value
};
render() {
return (
<React.Fragment>
Selected: {this.state.selected}
<select value={this.state.selected} onChange={this.handleChange}>
<option value="1m">1m</option>
<option value="5m">5m</option>
<option value="15m">15m</option>
<option value="30m">30m</option>
<option value="1h">1h</option>
<option value="4h">4h</option>
<option vlaue="1d">1d</option>
</select>
</React.Fragment>
);
}
}
关于javascript - 访问下拉列表的 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57469851/