티스토리 뷰
반응형
일반적인 방식으로 사용할 수 있는 일부 구성 요소를 정의하는 적절한 방법을 찾으려고 합니다.
<Parent>
<Child value="1">
<Child value="2">
</Parent>
<select>물론 부모와 자식 구성 요소 사이에 렌더링을 위한 논리가 있습니다. 이 논리 의 <option>예로 상상할 수 있습니다 .
이것은 질문의 목적을 위한 더미 구현입니다.
var Parent = React.createClass({
doSomething: function(value) {
},
render: function() {
return (<div>{this.props.children}</div>);
}
});
var Child = React.createClass({
onClick: function() {
this.props.doSomething(this.props.value); // doSomething is undefined
},
render: function() {
return (<div onClick={this.onClick}></div>);
}
});
문제는 래퍼 구성 요소를 정의하는 데 사용할 때마다 {this.props.children}일부 속성을 모든 자식에게 어떻게 전달합니까?
새로운 소품으로 아이들 복제하기
를 사용 React.Children하여 자식을 반복한 다음 를 사용하여 새 소품(얕게 병합됨)으로 각 요소를 복제 할 수 있습니다 React.cloneElement.
React Top-Level API – React
A JavaScript library for building user interfaces
reactjs.org
const Child = ({ doSomething, value }) => (
<button onClick={() => doSomething(value)}>Click Me</button>
);
function Parent({ children }) {
function doSomething(value) {
console.log("doSomething called by child with value:", value);
}
const childrenWithProps = React.Children.map(children, child => {
// Checking isValidElement is the safe way and avoids a typescript
// error too.
if (React.isValidElement(child)) {
return React.cloneElement(child, { doSomething });
}
return child;
});
return <div>{childrenWithProps}</div>
}
function App() {
return (
<Parent>
<Child value={1} />
<Child value={2} />
</Parent>
);
}
ReactDOM.render(<App />, document.getElementById("container"));
<script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<div id="container"></div>
자식을 함수로 호출하기
또는 render props 를 사용하여 props를 자식에게 전달할 수 있습니다 . 이 접근 방식에서 children( children또는 다른 prop 이름일 수 있음)은 전달하려는 모든 인수를 수락하고 하위를 반환할 수 있는 함수입니다.
const Child = ({ doSomething, value }) => (
<button onClick={() => doSomething(value)}>Click Me</button>
);
function Parent({ children }) {
function doSomething(value) {
console.log("doSomething called by child with value:", value);
}
// Note that children is called as a function and we can pass args to it.
return <div>{children(doSomething)}</div>
}
function App() {
// doSomething is the arg we passed in Parent, which
// we now pass through to Child.
return (
<Parent>
{doSomething => (
<React.Fragment>
<Child doSomething={doSomething} value={1} />
<Child doSomething={doSomething} value={2} />
</React.Fragment>
)}
</Parent>
);
}
ReactDOM.render(<App />, document.getElementById("container"));
<script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<div id="container"></div>반응형
'프로그래밍 > Front-End' 카테고리의 다른 글
| CSS를 사용하여 HTML5 input의 Placeholder 색상 변경 (0) | 2022.01.20 |
|---|---|
| css 텍스트 선택 강조 표시를 비활성화하는 방법 (0) | 2022.01.20 |
| npx와 npm의 차이점은 무엇입니까? (0) | 2022.01.20 |
| React.js에서 배열 자식의 유니크 키 이해하기 (0) | 2022.01.20 |
| React에서 이 세 개의 점은 무엇을 합니까? (0) | 2022.01.20 |
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- ChatGPT
- SWiFT
- HTML
- 오리역
- MacOS
- golang
- 부동산
- AI
- openai
- 카톡업데이트
- Frontend
- 카카오톡
- Linux
- Java
- 재테크
- 생각
- 개발자
- Spring
- go
- ios
- Backend
- JavaScript
- 부동산분석
- 내집마련
- react
- Python
- reactjs
- 프로그래밍
- CSS
- 주식투자
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | 31 |
글 보관함