[英]How to display a dropdown options when clicking in a button?
I need to display the dropdown options of a select when I click on a button. 当我点击按钮时,我需要显示选择的下拉选项。
I tried with the ref and focus or click but it's not working. 我尝试使用参考和焦点或点击但它不起作用。
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const [value, setValue] = React.useState(false);
const selectRef = React.useRef();
const handleClick = () => {
// selectRef.current.focus();
selectRef.current.click();
};
return (
<div className="App">
<button onClick={handleClick}>click me !</button>
<select
open
ref={selectRef}
value={value ? "activate" : "deactivate"}
onChange={e => setValue(e.target.value === "activate")}
>
<option value="activate">Activate</option>
<option value="deactivate">Deactivate</option>
</select>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
I need when I click on the button the select show me the dropdown options 当我点击按钮时,我需要选择向我显示下拉选项
I recommend you to see the below link. 我建议你看下面的链接。 I think that's what which you are looking for: https://medium.com/@wwayne_me/how-to-manually-open-select-in-react-1169967eb33b 我认为这就是你要找的东西: https : //medium.com/@wwayne_me/how-to-manually-open-select-in-react-1169967eb33b
In summary it talks about an attribute named size
which with setting it to non-zero
value you can set the select open and with setting it to zero
it will be closed. 总之,它讨论了一个名为size
的属性,通过将其设置为non-zero
值,您可以将select设置为open,并将其设置zero
,它将被关闭。
So your code would be like this: 所以你的代码是这样的:
const handleClick = () => {
selectRef.size=10;// optional number based on you
};
Try it and let me know if it works out. 尝试一下,让我知道它是否成功。
This is one way of doing it: 这是一种方法:
See if that works for you. 看看它是否适合你。
function App() { const [openDrop,setOpenDrop] = React.useState(false); function toggleDrop() { setOpenDrop((prevState)=>!prevState); } return( <React.Fragment> <button onClick={toggleDrop}>Drop</button> <div className="main"> App {openDrop && <Dropdown/>} </div> </React.Fragment> ); } function Dropdown() { function doSomething() { console.log('Let me handle this...'); } return( <div> <ul> <li onClick={doSomething}>Item 1</li> <li onClick={doSomething}>Item 2</li> </ul> </div> ); } ReactDOM.render(<App/>, document.getElementById('root'));
.main { background-color: lightblue; } li { cursor: pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script> <div id="root"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.