React 하위 요소에서 DOM 노드를 가져오는 중
사용방법React.findDOMNode
v0.13.0에서 도입된 방법: 매핑을 통해 부모에게 전달된 각 자식 컴포넌트의 DOM 노드를 가져올 수 있습니다.this.props.children
.
그러나 일부 어린이가 구성 요소가 아닌 반응 요소인 경우(예: 한 어린이가<div>
JSX를 통해 생성된 React는 불변 위반 오류를 발생시킵니다.
자녀가 어떤 클래스에 속하든 마운트 후 각 자녀의 올바른 DOM 노드를 얻을 수 있는 방법이 있습니까?
this.props.children
ReactElement 또는 ReactElement 배열 중 하나여야 하지만 컴포넌트는 아니어야 합니다.
하위 요소의 DOM 노드를 가져오려면 해당 요소를 복제하고 새 참조를 할당해야 합니다.
render() {
return (
<div>
{React.Children.map(this.props.children, (element, idx) => {
return React.cloneElement(element, { ref: idx });
})}
</div>
);
}
그런 다음 다음 를 통해 하위 구성 요소에 액세스할 수 있습니다.this.refs[childIdx]
를 사용하여 DOM 노드를 취득합니다.ReactDOM.findDOMNode(this.refs[childIdx])
.
임의의 DOM 요소에 액세스 하고 싶은 경우는, 다음의 순서에 따라 주세요.ref
해당 요소에 직접 액세스할 수 있습니다.
<input type="text" ref="myinput">
다음으로 직접 다음을 수행할 수 있습니다.
componentDidMount: function()
{
this.refs.myinput.select();
},
사용할 필요가 없습니다.ReactDOM.findDOMNode()
를 추가한 경우ref
모든 요소에 적용할 수 있습니다.
이는 refs 속성을 사용하면 가능합니다.
에 도달하고 싶은 예에서는<div>
사용하고 싶은 것은,<div ref="myExample">
그러면 DOM 노드를 사용할 수 있습니다.React.findDOMNode(this.refs.myExample)
.
거기서 각 자식의 올바른 DOM 노드를 얻는 것은 매핑하는 것만큼이나 간단할 수 있습니다.this.refs.myExample.children
(아직 테스트하지 않았지만) ref 속성을 사용하여 특정 마운트된 하위 노드를 가져올 수 있습니다.
자세한 내용은 레퍼런스 관련 공식 반응 문서입니다.
이것은 새로운 React ref api를 사용하여 실행할 수 있습니다.
function ChildComponent({ childRef }) {
return <div ref={childRef} />;
}
class Parent extends React.Component {
myRef = React.createRef();
get doSomethingWithChildRef() {
console.log(this.myRef); // Will access child DOM node.
}
render() {
return <ChildComponent childRef={this.myRef} />;
}
}
React.findDOMNode(this.refs.myExample)
다른 답변에서 언급된 내용은 수정되었습니다.
사용하다ReactDOM.findDOMNode
부터'react-dom'
대신
import ReactDOM from 'react-dom'
let myExample = ReactDOM.findDOMNode(this.refs.myExample)
새로운 콜백 레퍼런스를 사용하여 간단한 방법을 찾았습니다.콜백을 소품으로 자 컴포넌트에 전달할 수 있습니다.다음과 같이 합니다.
class Container extends React.Component {
constructor(props) {
super(props)
this.setRef = this.setRef.bind(this)
}
setRef(node) {
this.childRef = node
}
render() {
return <Child setRef={ this.setRef }/>
}
}
const Child = ({ setRef }) => (
<div ref={ setRef }>
</div>
)
다음으로 모달에서 이를 수행하는 예를 나타냅니다.
class Container extends React.Component {
constructor(props) {
super(props)
this.state = {
modalOpen: false
}
this.open = this.open.bind(this)
this.close = this.close.bind(this)
this.setModal = this.setModal.bind(this)
}
open() {
this.setState({ open: true })
}
close(event) {
if (!this.modal.contains(event.target)) {
this.setState({ open: false })
}
}
setModal(node) {
this.modal = node
}
render() {
let { modalOpen } = this.state
return (
<div>
<button onClick={ this.open }>Open</button>
{
modalOpen ? <Modal close={ this.close } setModal={ this.setModal }/> : null
}
</div>
)
}
}
const Modal = ({ close, setModal }) => (
<div className='modal' onClick={ close }>
<div className='modal-window' ref={ setModal }>
</div>
</div>
)
언급URL : https://stackoverflow.com/questions/29568721/getting-dom-node-from-react-child-element
'source' 카테고리의 다른 글
새 메뉴 항목 만들기 - Wordpress (0) | 2023.03.16 |
---|---|
게스트 사용자에 대해 woocommerce_sys_add_to_syslog가 작동하지 않음 (0) | 2023.03.16 |
AngularJS : 파일 연결로 인해 모듈 선언 순서가 깨집니다. (0) | 2023.03.16 |
문 lamda는 식 lamda로 대체할 수 있습니다. (0) | 2023.03.16 |
Apache의 mod_php 또는 Fast CGI?워드프레스에 어떤 게 좋을까요? (0) | 2023.03.16 |