React - 表单组件实现

一、介绍

本文将会基于react实现表单的功能,包括表单提交和跳转、错误处理、动态表单元素、动态内容加载。

二、使用教程

1.表单提交功能

javascript 复制代码
export default class FormSubmit extends React.PureComponent{
    
    state = {
        name: ""
    }

    handleNameChange = evt => {
        this.setState({
            name: evt.target.value
        });

    }

    handleSubmit = evt => {
        evt.preventDefault(); // 阻止默认事件
        if (!this.state.name){
            this.setState({error: "Name is required"});
            return;
        }
        fetchUserList(this.state.name);        
    }
    
    const {userState, fetchUserList} = useFetchUserList();

    render(){
        return (
            <>
            <form className = "comment-box" onSubmit = {this.handleSubmit}>
                <div>
                    <label>Name:</label> 
                    <input value = {this.state.name} onchange = {this.handleNameChange}/>
                </div>
                
                <div>
                    <button>Submit</button>
                </div>
            </form>
            {userState.data && <ul>userState.data.map((user)=> <li>user.name</li>)</ul>}
            </>
        )    
    
    }


    

}

user-service.js

javascript 复制代码
const initialState = {data:[], isLoading:false, error:null};

// reducer
function reducer(state, action){
    switch (action.type){
        case FETCH_USER_LIST_BEGIN:
            return (data:[action.res.data], isLoading: true, error:null);
        case FETCH_USER_LIST_SUCCESS:
            return (...state, isLoading: false, error:null);
        case FETCH_USER_LIST_ERROR:
            return (...state, isLoading: false, 
                    error:res.data.error);
    
    }
    
}

const [state, dispatch] = useReducer(reducer, initialState);

function fetchUserList(){

     dispatch({type: FETCH_USER_LIST_BEGIN});    
     
     const doRequest = axios.get("http://www.user.com/user/list");
     doRequest.then(
                res => {
                    dispatch({
                        type: FETCH_USER_LIST_BEGIN,
                        data: res.data
                    });
                },
                err => {
                    dispatch({
                        type: FETCH_USER_LIST_ERROR,
                        data: {error:err}
                        }
                    );
          
                }
            );
}


export default userFetchUserList = () => {state, fetchUserList}

2.动态表单元素 (TODO)

相关推荐
Doris_202313 小时前
说一说ESLint+Prettier生效的原理
前端·设计模式·架构
ZC跨境爬虫14 小时前
跟着 MDN 学CSS day_21:(图像溢出控制与表单元素样式定制)
前端·javascript·css·ui·交互
卷帘依旧14 小时前
微前端解决方案-qiankun
前端
moshuying14 小时前
你做的,比汇报出来的多得多
前端
shuye21614 小时前
google chrome 离线下载地址
前端·chrome
yqcoder14 小时前
闭包是什么?优缺点、怎么防内存泄漏?
前端·http
lichenyang45314 小时前
鸿蒙 ArkUI 组件基础复盘:从两个 UI 卡片回到 ComponentV2、状态管理和组件分层
前端
biubiubiu_LYQ14 小时前
萌新小白基础理解篇之 this 关键字
前端·javascript
光影少年15 小时前
Redux 中间件作用(redux-thunk/redux-saga)
前端·react.js·掘金·金石计划
爱上好庆祝15 小时前
学习JS第十一天(JS的进阶)
前端·javascript·学习