我希望使用Downshift
将网址链接添加到以下脚本中我处于图书状态,具有名称和链接属性。这些书的名称在下拉列表中可以很好地显示,但是我想知道如何最好地提取用于每个下拉元素的链接。我希望下拉列表,例如单击“哈利波特”书,该书将链接到“哈利波特”页面。
这是我正在使用的代码:
CodeSandbox: https://codesandbox.io/s/dropdown-with-downshift-1c978?fontsize=14
import React, { Component } from "react";
import ReactDOM from "react-dom";
import Downshift from "downshift";
import "./styles.css";
class DownshiftThree extends Component {
constructor(props) {
super(props);
this.books = [
{ name: "Harry Potter", link: "/harry-potter" },
{ name: "Net Moves", link: "/net-moves" },
{ name: "Half of a yellow sun", link: "/yellow-sun" },
{ name: "The Da Vinci Code", link: "/da-vinci-code" },
{ name: "Born a crime", link: "/born-a-crime" }
];
this.state = {
selectedBook: ""
};
this.onChange = this.onChange.bind(this);
}
onChange(selectedBook) {
this.setState({ selectedBook: selectedBook.name });
}
render() {
return (
<Downshift
onChange={this.onChange}
selectedItem={this.state.selectedBook}
itemToString={books => (books ? books.name : "")}
>
{({
isOpen,
getToggleButtonProps,
getItemProps,
highlightedIndex,
selectedItem: dsSelectedItem,
getLabelProps
}) => (
<div>
<label
style={{ marginTop: "1rem", display: "block" }}
{...getLabelProps()}
>
Select your favourite book
</label>{" "}
<br />
<button className="dropdown-button" {...getToggleButtonProps()}>
{this.state.selectedBook !== ""
? this.state.selectedBook
: "Select a book ..."}
</button>
<div style={{ position: "relative" }}>
{isOpen ? (
<div className="downshift-dropdown">
{this.books.map((item, index) => (
<div
className="dropdown-item"
{...getItemProps({ key: index, index, item })}
style={{
backgroundColor:
highlightedIndex === index ? "lightgray" : "white",
fontWeight: dsSelectedItem === item ? "bold" : "normal"
}}
>
<a href="{item.link}">{item.name}</a>
</div>
))}
</div>
) : null}
</div>
</div>
)}
</Downshift>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<DownshiftThree />, rootElement);