我在 react-ts 中写了一个小的自定义组件,它包装了一个具有一些附加功能的
<input />
,主要是通过选项列表进行模糊搜索。我打算在表格中使用它。
但是现在我创建了组件,我无法在
<form>
中检索它的值,因为它不是 html 元素并且没有我可以读取的 value
属性。
我正在阅读文档here,但这对我没有帮助。我还尝试用谷歌搜索“反应形式的自定义输入”、“从自定义反应组件获取价值”等,但找不到任何结果,尽管我确信这对很多人来说应该是一件非常简单的事情.我能找到的最接近的结果是this,答案对我一点帮助都没有。
成分:
export interface SmartInputProps {
items: any[],
itemKey: string
//[...]
}
export const SmartInput: React.FC<SmartInputProps> = ({
items,
itemKey = 'name'
//[...]
}: SmartInputProps) => {
// [...]
// (lots of funcionality)
return (
<div>
<input /*[...]*/ />
//some more visual stuff, like displaying list of results
</div>
);
}
以及我要在其中使用组件的形式
interface Props {
className?: string
}
export const SearchBar: React.FC<Props> = () => {
// [...]
return (
<div className="searchbar-wrapper">
<form onSubmit={handleSubmit}>
<SmartInput
items={options}
itemKey='name'
//[...]
/>
<input type='submit' value='OK' />
</form>
</div>
);
}
我想访问表格中
value
里面的<input />
的当前<SmartInput />
。
我尝试使用 hacky 方式获取值,例如将
onChange
的 <input />
向上委派(如 proposed here),但这只允许我在触发 onChange
时获取和存储值,不要在提交时阅读它。这种解决方法确实允许我在提交时使用该值,但我必须先处理每一个 onChange
,这是次优的。
useRef
找到了更好的解决方案,它也更优雅。
使用最初的例子:
interface Props {
className?: string
}
export const SearchBar: React.FC<Props> = () => {
const inputRef = useRef<HTMLInputElement>(null); //<- here
// [...]
return (
<div className="searchbar-wrapper">
<form onSubmit={handleSubmit}>
<SmartInput
items={options}
itemKey='name'
ref={inputRef} //<- here
//[...]
/>
<input type='submit' value='OK' />
</form>
</div>
);
}
我们在组件中添加一个带有输入类型接口的
useRef
。然后我们将它作为道具传递给自定义组件<SmartInput />
。
接收组件一侧:
export interface SmartInputProps {
items: any[],
itemKey: string,
ref: MutableRefObject<HTMLInputElement> //<- here
//[...]
}
export const SmartInput: React.FC<SmartInputProps> = ({
items,
itemKey = 'name',
ref, //<- here
//[...]
}: SmartInputProps) => {
// [...]
// (lots of funcionality)
return (
<div>
<input ref={ref} /*<- here*/ /*[...]*/ />
//some more visual stuff, like displaying list of results
</div>
);
}
我们将 ref 添加到自定义组件道具并将其传递给我们自定义组件内的香草 html 输入字段的
ref
属性。
不,我们可以从根引用对象查询字段状态。
例如
let fieldValue = inputRef.current.value
.