我试图将数组中第一个对象的属性显示为默认项。当我尝试提交表单时,我得到的选择值为空,因为我还没有参与它。我如何确保该值存在?我正在使用react-bootstrap. 以下是代表此问题的代码片段:这里是重点,我不知道值字段应该放什么。我想要的是引用该id值,如果我的数组中只有一项,我不必打开下拉列表,id 已经在那里:<Form.Control as="select" value={WHAT DO I DO HERE??} onChange={props.handleCart}> {props.carts.map((cart,i) => <option key={cart.id} value={cart.id}>{cart.cart_name</option>)}) </Form.Control>主页.jsconstructor() { super(); this.state = { myCarts = [ {'id':'1', 'cart_name': 'my cart 1'}, {'id':'2', 'cart_name': 'my cart 2'} ],showMenu: false}}...Return<CreateshowMenu = {this.state.showMenu}menuModalToggle={this.menuModalToggle} carts = {this.state.carts}/>创建.jsconst CreateMenuModal = (props) => { console.log('props carts there?',props.carts); return ( <Modal //dialogClassName={classes.modal} show={props.showMenu} onHide={props.menuModalToggle} > <Modal.Header closeButton> <Modal.Title>Create Menu</Modal.Title> </Modal.Header> <div style={{ textAlign: 'center', padding: 10 }}> Fill out the following details to create menus for your cart. Once you create a menu you will have the option to add and remove items from that menu. </div> <Modal.Body> <Form> <Form.Group controlId="cart_check"> <Form.Label>Choose which cart this menu is for:</Form.Label> <Form.Control as="select" value={WHAT DO I DO HERE??} onChange={props.handleCart}> {props.carts.map((cart,i) => <option key={cart.id} value={cart.id}>{cart.cart_name}</option>)}) </Modal> )}
1 回答
慕田峪4524236
TA贡献1875条经验 获得超5个赞
你可以尝试defaultValue form-control-props
<Form.Control
as="select"
value={props.carts[0].id.toString()}
defaultValue={props.carts[0].id.toString()}
onChange={props.handleCart}
>
{props.carts.map((cart,i) => (
<option key={cart.id} value={cart.id}>
{cart.cart_name}
</option>
))}
</Form.Control>
添加回答
举报
0/150
提交
取消