在React中,可以通过使用useState或useRef钩子来解决不能在多个组件实例之间共享表单控件实例的问题。
方法一:使用useState钩子
import React, { useState } from 'react';
const MyComponent = () => {
const [inputValue, setInputValue] = useState('');
const handleChange = (e) => {
setInputValue(e.target.value);
};
return (
);
};
export default MyComponent;
方法二:使用useRef钩子
import React, { useRef, useEffect } from 'react';
const MyComponent = () => {
const inputRef = useRef();
useEffect(() => {
const handleInputChange = (e) => {
console.log(e.target.value);
};
inputRef.current.addEventListener('input', handleInputChange);
return () => {
inputRef.current.removeEventListener('input', handleInputChange);
};
}, []);
return (
);
};
export default MyComponent;
无论使用useState还是useRef,都能确保每个组件实例都有自己独立的表单控件实例,避免了共享的问题。
上一篇:不能在类组件中返回JSX。