先说一下效果要求,上面一个下拉框,下面一个,要求上面选中的时候,下面的内容要跟着变。
因为想到react是数据驱动的,就不打算再用jq的那种隐藏显示了,而是通过在执行类型下拉框的onChange事件中,去改变下面的下拉框的数据,渲染出不同的下拉选择。
定义数据:modeOptions是各个下拉框的值,由于选中号码的时候是输入框,这里号码的options为空。
constructor(props) { super(props) this.modeOptions = { 'channelMode': {options: ['通道1','通道2','通道3','通道4'],text: '通道'},'batchMode': {options: [1,2,3,4,5],text: '批次'},'numberMode': {options: [],text: '号码'},'areaMode': {options: ['福州市','厦门市'],text: '区域'} } this.state = { selectMode: 'channelMode' } this.selectMode = this.selectMode.bind(this) }
然后在下拉框的选中事件中去设置seletMode的值,发现antd的下拉框只要直接定义onChange事件,回调函数的第一个参数就是selectMode的值。
selectMode(value) { this.setState({ selectMode: value }) }
然后在render里面进行一下数据处理
let modelLabel = this.modeOptions[this.state.selectMode].text; let modelOptions = null; if(this.modeOptions[this.state.selectMode].options.length !== 0) { modelOptions = []; this.modeOptions[this.state.selectMode].options.map((item,index) => { modelOptions.push(<option key={index}>{item}</option>); }) }
贴下代码:其实就是当选中的不是号码时,在第二个下拉框组件用上面的modelLabel和modelOptions来渲染下拉框,如果选择的是号码,就渲染一个输入框。
class DemandForm extends React.Component { constructor(props) { super(props) this.modeOptions = { 'channelMode': {options: ['通道1',text: '区域'} } this.state = { selectMode: 'channelMode' } this.selectMode = this.selectMode.bind(this) } handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFieldsAndScroll((err,values) => { if (!err) { console.log('Received values of form: ',values); } }); } selectMode(value) { this.setState({ selectMode: value }) } render() { const { getFieldDecorator } = this.props.form; const formItemLayout = { labelCol: { xs: { span: 24 },sm: { span: 6 },},wrapperCol: { xs: { span: 24 },sm: { span: 18 },}; let modelLabel = this.modeOptions[this.state.selectMode].text; let modelOptions = null; if(this.modeOptions[this.state.selectMode].options.length !== 0) { modelOptions = []; this.modeOptions[this.state.selectMode].options.map((item,index) => { modelOptions.push(<option key={index}>{item}</option>); }) } return ( <Form className="blackForm" onSubmit={this.handleSubmit}> <FormItem {...formItemLayout} label="定点执行类型:" hasFeedback > {getFieldDecorator('selectMode',{ rules: [ { required: true,message: 'Please select your country!' },],})( <Select onChange={this.selectMode} placeholder="Please select a country"> <Option value="channelMode">按通道</Option> <Option value="numberMode">按号码</Option> <Option value="areaMode">按区域</Option> <Option value="batchMode">按批次</Option> </Select> )} </FormItem> <FormItem {...formItemLayout} label={modelLabel} hasFeedback > {getFieldDecorator('mode',})( this.state.selectMode !== 'numberMode' ? <Select placeholder="Please select a country">{modelOptions}</Select> : <Input placeholder="请输入电话号码" /> )} </FormItem> </Form> ); } } const WrappedDemandForm = Form.create()(DemandForm);原文链接:https://www.f2er.com/react/301489.html