【发布时间】:2019-12-04 06:52:43
【问题描述】:
我在一个组件中有一个带有 ref 的文本框(modalBox.js)我如何在按钮单击时访问另一个组件上的文本框的值,例如(index.js)
【问题讨论】:
标签: reactjs react-component react-ref
我在一个组件中有一个带有 ref 的文本框(modalBox.js)我如何在按钮单击时访问另一个组件上的文本框的值,例如(index.js)
【问题讨论】:
标签: reactjs react-component react-ref
在 react 中检查 refForwarding。 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>;
【讨论】: