react控制元素的显示或隐藏
生活随笔
收集整理的這篇文章主要介紹了
react控制元素的显示或隐藏
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
如圖所有,當我選擇公司性質為 “默認” 或者 “個人” 時候 ‘公司全稱’字段是隱藏。當我們選擇公司性質為“公司”時 ‘公司全稱’字段展示。
默認狀態:
公司性質為“公司”
這個功能該如何實現呢?
思路:
1.在‘公司性質’這個 select框上面綁定一個 onchange事件,每次變化 獲取到當前select框 對應的值。
2.將獲取到當前select框的值寫一個接口去調用它(如果使用react, 則在 reducer里面定義),并將每次返回的值在傳遞給前端頁面;
3.根據接口返回的select的值來對應顯示“公司性質”的顯示或者隱藏。
代碼:
newEdit.js — view層 — 父組件
import Form from './components/basicForm';onSwitchAccountCategory = (value) => { /*將從接口獲取到的數據子組件 ,這里傳遞了所有的props數據,和一個函數onSwitchAccountCategory ,傳遞的函數用于從子組件獲取到select框的值傳遞給父組件*/this.props.dispatch({type: `${this.module}/switchAccountCategory`,payload: value});}buildForm = (props) => {return (<Form {...props} onSwitchAccountCategory={this.onSwitchAccountCategory} />);}basicForm.js — view層—子組件
import { FormInputField } from 'components/common';render = () => {let { entity } = this.props; return (<Form><FormInputFieldgetFieldDecorator={getFieldDecorator}label="公司性質"fieldProps={{style: {width: 120 }, onChange: this.props.onSwitchAccountCategory}} /*onChange 方法 */field="accountCategory"fieldDecoratorOptions={{rules: [{required: true,message:'請選擇公司性質'}],validateTrigger: ['onSubmit']}}entity={entity}datasource={CompanyNature.toArray().map(item => ({ text: item.text, id: item.value }))}type="select"/>/*---------------------------------------------------------------------------------------*/ /* 將獲取的select框的值轉換,判斷是否等于公司來控制其 顯示 或者 隱藏*/{CompanyNature.getAliasFromValue(entity.accountCategory) === '公司' &&<FormInputFieldgetFieldDecorator={getFieldDecorator}label="公司全稱"field="companyName"required={false}fieldDecoratorOptions={{rules: [{required: false,whitespace: true,message: "請輸入公司全稱"},{validator: this.verifyCompanyName,}],validateTrigger: ['onSubmit']}}entity={entity}key="companyName"/>}</Form>) )edit.js — Model層
reducers: {switchAccountCategory(state, action) { //切換公司性質return {...state,entity: {...state.entity,accountCategory: action.payload /* 將獲取到的select框的值傳遞給view層 */ }};},總結
以上是生活随笔為你收集整理的react控制元素的显示或隐藏的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 公主连接升6星条件 迪士尼公主大盘点
- 下一篇: 上官婉儿天狼绘梦者什么时候出 王者荣耀上