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)

相关推荐
Shi_haoliu9 小时前
openClaw源码部署-linux
前端·python·ai·openclaw
程序员小寒9 小时前
前端性能优化之白屏、卡顿指标和网络环境采集篇
前端·javascript·网络·性能优化
烛阴9 小时前
Claude CLI AskUserQuestion 工具详解:让 AI 开口问你
前端·claude
wal131452010 小时前
OpenClaw教程(九)—— 彻底告别!OpenClaw 卸载不残留指南
前端·网络·人工智能·chrome·安全·openclaw
mon_star°10 小时前
在TypeScript中,接口MenuItem定义中,为什么有的属性带问号?,有的不带呢?
前端
牛奶10 小时前
分享一个开源项目,让 AI 辅助开发真正高效起来
前端·人工智能·全栈
次顶级11 小时前
表单多文件上传和其他参数处理
前端·javascript·html
why技术11 小时前
我拿到了腾讯QClaw的内测码,然后沉默了。
前端·后端
谪星·阿凯12 小时前
XSS漏洞解析博客
前端·web安全·xss