seo做的最好的网站,建设部住房城乡建设厅网站,免费做旅游海报的网站,宁夏网站建设品牌公司通过React.createRef → ref对象通过元素的ref属性可以附加到React元素上一般通过构造器中给this的属性赋值一个ref#xff0c;方便整个组件使用ref只要传递到react元素中#xff0c;就可以利用ref的current属性访问到该真实DOM节点ref在componentDidMount和componentDidUpda…通过React.createRef → ref对象通过元素的ref属性可以附加到React元素上一般通过构造器中给this的属性赋值一个ref方便整个组件使用ref只要传递到react元素中就可以利用ref的current属性访问到该真实DOM节点ref在componentDidMount和componentDidUpdate触发前更新
current里是null的现象
由于打印时this.modalRef才刚刚声明current是null但是current是个引用值展开时访问的是最后的结果
class Modal extends React.Component {constructor(props) {super(props)this.modalRef React.createRef()console.log(刚创建时, this.modalRef)}componentDidMount() {console.log(componentDidMount, this.modalRef)}componentDidUpdate() {console.log(componentDidUpdate, this.modalRef)}render() {return (divref{this.modalRef}style{{width: 300px,border: 1px solid #000,display: this.props.toOpen ? block : none}}h1This is a Modal/h1pThis is a super Modal/p/div)}
}ref有不同的使用方式
ref放在html元素上 → current: 真实DOMref放在class组价上 → current: 组件实例ref放在函数组件没有实例→ 无法附加到组件上
class App extends React.Component {constructor(props) {super(props)this.refInApp React.createRef()}state {toOpen: false,}componentDidMount() {console.log(【APP】componentDidMount, this.refInApp)}changeStatus (toOpen) {this.setState({toOpen})}render() {return (Modal toOpen{this.state.toOpen} ref{this.refInApp} /button onClick{() this.changeStatus(true)}打开/buttonbutton onClick{() this.changeStatus(false)}关闭/button/)}
}函数组件使用hooks获取dom实例
function Test() {const divRef React.useRef(null)React.useEffect(() {console.log(函数组件使用hooks获取ref, divRef)}, [])return (div ref{divRef}Test函数组件/div)
}若试图在函数组价上传ref属性会告警
Test ref{this.refInApp} /