a-select defaultValue="默認選項">
2、設(shè)置value屬性
a-select value="默認選項">
3、通過option的key屬性設(shè)置默認選項
a-select>
const options = [ { value: '1', label: '默認值1' }, { value: '2', label: '默認值2' }, { value: '3', label: '默認值3' }, ]; a-select defaultValue="1" options={options}>
在上述例子中,我們通過定義一個options數(shù)組,在數(shù)組元素中定義了value和label兩個屬性,分別對應(yīng)選項的值和顯示的文本。這樣,當我們設(shè)置defaultValue為"1"時,a-select便會默認選中"value"值為"1"的選項。
在getFieldDecorator方法中,我們通過配置initialValue屬性來設(shè)置a-select的默認值。當我們在表單提交的時候,getFieldValue方法便可以獲取到當前選中的值。
import React, { useState } from 'react'; import { Select } from 'antd'; function MyComponent(props) { const [defaultValue, setDefaultValue] = useState('1'); function handleChange(value) { setDefaultValue(value); } return ( ); }
在上述例子中,我們通過useState Hook來創(chuàng)建一個名為defaultValue的狀態(tài)變量,并將初始值設(shè)置為"1"。當用戶選擇其他選項時,handleChange函數(shù)會觸發(fā)并更新defaultValue狀態(tài)變量,從而實現(xiàn)動態(tài)的默認值設(shè)置。
import React, { Component } from 'react'; import { Select } from 'antd'; import { connect } from 'react-redux'; class MyComponent extends Component { handleChange = (value) => { const { dispatch } = this.props; dispatch({ type: 'updateDefaultValue', payload: value, }); } render() { const { defaultValue } = this.props; return ( ); } } function mapStateToProps(state) { const { defaultValue } = state; return { defaultValue, }; } export default connect(mapStateToProps)(MyComponent);
在上述例子中,我們首先使用connect方法連接MyComponent組件和redux的store。然后,通過mapStateToProps方法將store中的defaultValue屬性映射到MyComponent組件的props屬性中。在handleChange方法中,我們通過dispatch方法派發(fā)一個type為"updateDefaultValue"的action,payload為用戶選擇的value值,從而觸發(fā)store中的reducer更新defaultValue屬性。最后,我們使用Select組件來展示選項列表,并設(shè)置defaultValue屬性為props中的defaultValue屬性。