我有一个在一个组件中带有 ref 的文本框(modalBox.js( 如何在单击按钮时访问另一个组件(如(索引.js((上的文本框的值
check refForwarding in react. https://reactjs.org/docs/forwarding-refs.html
假设您在Component1
中有一个input
字段 -
const Component1 = props => {
let textInput = useRef(null);
const handleOnChange = event => {
props.onChange(textInput)
}
return (
<input onChange={handleOnChane} ref={textInput} />
)
}
现在从另一个组件,你想要捕获引用 -
<Component1 onChange = {ref => console.log(ref) } />
在这里,我只是在控制台中打印 ref 对象。但你可以做任何你想做的事。
const MyComponent = React.forwardRef((props, ref) => (
<button ref={ref}>
Click me
</button>
));
const ref = React.createRef();
<MyComponent ref={ref}>Click me!</MyComponent>;