【发布时间】:2021-03-15 19:08:53
【问题描述】:
我正在创建一个应用程序,我试图在其中建立一个“activeCat”,同时从下拉菜单中选择它。我可以切换“activeCat”的状态,但它只包含猫(对象)的“昵称”。
这是我的 CatList 组件(下拉菜单)
import axios from 'axios';
import {Dropdown} from 'react-bootstrap';
export default class CatList extends Component {
constructor(props) {
super(props)
this.state = {
cats: [],
activeCat:''
}
}
onClickHandler = event => {
const activeCat = event.target.innerHTML;
this.setState({ activeCat })
console.log(activeCat)
{this.state.cats.map((cat, index)=>{
console.log(cat, index)
if(index == this.state.activeCat){
console.log(cat._id)
return(
<div >
Hello
</div>
)
}})}
}
componentDidMount() {
this.getCollection('All')
}
//get entire collection
getCollection = (_Id) => {
axios
.get(`http://localhost:5000/api/kittys/getByUserId/${this.props.user._id}`)
.then(res => {
const cats = res.data
this.setState({cats: cats})
})
}
render() {
return (
<div>
<p style={{display:"flex", justifyContent:"center"}}>Selected Cat: {this.state.activeCat}</p>
<Dropdown
style={{display:"flex", justifyContent:"center"}}
className="cat-list">
<Dropdown.Toggle variant="success" id="dropdown-basic">
My Cats
</Dropdown.Toggle>
<Dropdown.Menu>
{this
.state
.cats
.map((kitty, index) => {
return (
<div key={index}>
<Dropdown.Item onClick={this.onClickHandler}>{kitty.nickName}</Dropdown.Item>
</div>
)
})}
</Dropdown.Menu>
</Dropdown>
</div>
)
}
}
这是单击下拉菜单中的第一项后我的控制台的图片(米妮)
CONSOLE AFTER USING THE ONCLICKHANDLER
here is a photo showing the dropdown and selected cat above
我希望能够像我一样在下拉菜单上方显示 ActiveCat 的名称,但我也希望其他猫的信息可用。
【问题讨论】:
标签: javascript reactjs forms api mapping