MST

星途 面试题库

面试题:React中事件代理在表单处理中的应用

假设你有一个包含多个输入框的表单,使用React的事件代理,如何实现当任意一个输入框内容变化时,在控制台打印出该输入框的值和其name属性?请写出关键代码。
25.8万 热度难度
前端开发React

知识考点

AI 面试

面试题答案

一键面试
import React, { useState } from 'react';

const FormComponent = () => {
    const [inputValue, setInputValue] = useState('');
    const handleInputChange = (e) => {
        const { value, name } = e.target;
        setInputValue(value);
        console.log(`值: ${value}, name属性: ${name}`);
    };

    return (
        <form>
            <input 
                type="text" 
                name="input1" 
                onChange={handleInputChange} 
                placeholder="输入框1"
            />
            <input 
                type="text" 
                name="input2" 
                onChange={handleInputChange} 
                placeholder="输入框2"
            />
        </form>
    );
};

export default FormComponent;