react 获取子组件的值 useRef
时间: 2023-05-18 09:02:57 浏览: 72
可以使用 useRef 钩子来获取子组件的值。首先,在子组件中使用 useRef 创建一个 ref 对象,然后将该 ref 对象传递给父组件。在父组件中,可以使用 ref.current 来获取子组件的值。以下是示例代码:
子组件:
```
import React, { useRef } from 'react';
function ChildComponent() {
const inputRef = useRef(null);
return (
<div>
<input type="text" ref={inputRef} />
</div>
);
}
export default ChildComponent;
```
父组件:
```
import React, { useRef } from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
const childInputRef = useRef(null);
const handleClick = () => {
console.log(childInputRef.current.value);
};
return (
<div>
<ChildComponent ref={childInputRef} />
<button onClick={handleClick}>获取子组件的值</button>
</div>
);
}
export default ParentComponent;
```
当点击按钮时,会在控制台中输出子组件输入框中的值。