这是我的自定义组件forwardRef。ref 在组件内部代码中是必需的,但父组件可以选择将其作为 prop 发送
const MyComponent = React.forwardRef((props, ref) => {
const handleButtonClick = () => {
// I need to access the ref here but, it's null
// when I not pass ref as prop to my component
}
return (
<>
<input type="text" ref={ref}/>
<button onClick={handleButtonClick}>Click</button>
</>
)
})
Run Code Online (Sandbox Code Playgroud)
我应该如何处理这个问题?我想要一个可选的 ref 作为道具,里面也需要它。
另外,我尝试useRef在我的组件中使用 并将转发的引用作为其初始值传递,在这种情况下,我无法访问父组件中的引用。
Shu*_*tri 12
useRef如果父级尚未传递引用,您可以使用定义 localRef
const MyComponent = React.forwardRef((props, ref) => {
const localRef = useRef(null);
const inputRef = ref || localRef;
const handleButtonClick = () => {
// I need to access the ref here but, it's null
// when I not pass ref as prop to my component
// access input using `inputRef.current`
}
return (
<>
<input type="text" ref={inputRef}/>
<button onClick={handleButtonClick}>Click</button>
</>
)
})
Run Code Online (Sandbox Code Playgroud)
然而,更好的做法是不使用 refs 来访问输入值,而是将输入作为受控组件并通过父级提供的 props 将此信息传递给父级
const MyComponent = React.forwardRef((props, ref) => {
const [value, setValue] = useState('')
const handleButtonClick = () => {
// access input value from state like
console.log(value);
props.handleSubmit && props.handleSubmit(value)
}
const handleChange = e => {
setValue(e.target.value);
}
return (
<>
<input type="text" value={value} onChange={handleChange} ref={inputRef}/>
<button onClick={handleButtonClick}>Click</button>
</>
)
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5388 次 |
| 最近记录: |