转发 Refs
是什么
- Ref 转发通过 forwardRef 将 父组件创建的 ref 通过 props 组件传递挂载到子组件,从而获取子组件的 DOM 节点数据。
- 对于大多数应用中的组件来说,这通常不是必需的。但其对某些组件,尤其是可重用的组件库是很有用的。
示例 1
// App.js
import React from "react";
import Child from "./Child";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.input = React.createRef(); // 1
// ↑5
}
handleClick = (e) => {
// 获取子组件
const input = this.input.current;
// 6
console.log(input);
console.log(input.value);
input.focus();
};
render() {
return (
<>
<button onClick={this.handleClick}>
父组件:转发refs获取子组件input值
</button>
{/*2*/}
<Child ref={this.input} />
</>
);
}
}
Foo.jsx
import React from "react";
// 3
const Child = React.forwardRef((props, myRef) => {
return (
<div style={{ border: "1px solid red", height: "50px", width: "200px" }}>
<input
type="text"
defaultValue="子组件:转发ref成功后才能打印"
ref={myRef}
/>
</div>
);
});
export default Child;
示例 2
import React from "react";
import "./styles.css";
const inputRef = React.createRef();
class App extends React.Component {
handleSave = () => {
console.log(inputRef.current.value);
};
render() {
return (
<div>
<TextInput ref={inputRef} />
<button onClick={this.handleSave}>保存</button>
</div>
);
}
}
const TextInput = React.forwardRef((props, ref) => (
<input type="text" placeholder="请输入表名" ref={ref} />
));
export default App;