{this.props.children}에게 소품을 전달하는 방법
일반적인 방법으로 사용할 수 있는 컴포넌트를 정의하는 적절한 방법을 찾고 있습니다.
<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}
래퍼 컴포넌트를 정의하려면 어떻게 하면 모든 자식에게 속성을 물려줄 수 있습니까?
새로운 소품으로 어린이 복제
를 사용하여 하위 요소에 대해 반복한 다음 를 사용하여 새 소품으로 각 요소를 복제할 수 있습니다(마지된 항목 표시).예를 들어 다음과 같습니다.
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>
함수로서의 자녀 호출
또는 렌더링 소품을 사용하여 소품을 아이들에게 전달할 수 있습니다.이 접근법에서 자녀는 다음과 같이 할 수 있습니다.children
또는 기타 소품명)은 전달하려는 인수를 모두 받아들일 수 있는 함수이며 하위 항목을 반환합니다.
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>
<React.Fragment>
간단히 말해서<>
필요에 따라 어레이를 반환할 수도 있습니다.
조금 더 깔끔하게 하려면 , 다음의 방법을 시험해 주세요.
<div>
{React.cloneElement(this.props.children, { loggedIn: this.state.loggedIn })}
</div>
편집: 여러 개별 하위 항목(자체 자체가 구성 요소여야 함)에서 사용할 수 있습니다.16.8.6에서 테스트 완료
<div>
{React.cloneElement(this.props.children[0], { loggedIn: true, testPropB: true })}
{React.cloneElement(this.props.children[1], { loggedIn: true, testPropA: false })}
</div>
이거 드셔보세요
<div>{React.cloneElement(this.props.children, {...this.props})}</div>
리액트-15.1을 사용했을 때 효과가 있었습니다.
{...this.props}
는 https://reactjs.org/docs/jsx-in-depth.html#spread-attributes 에서 제안되고 있습니다.
아이들에게 소품을 건네다.
기타 모든 답변 보기
컨텍스트를 통해 공유된 글로벌 데이터를 컴포넌트 트리에 전달
컨텍스트는 현재 인증된 사용자, 테마 또는 선호 언어 등 React 구성 요소의 트리에 대해 "글로벌"로 간주할 수 있는 데이터를 공유하도록 설계되었습니다.1
면책사항:이것은 갱신된 답변입니다.이전 답변은 오래된 컨텍스트 API를 사용했습니다.
Consumer / Provid 원칙에 근거합니다.첫째, 컨텍스트를 만듭니다.
const { Provider, Consumer } = React.createContext(defaultValue);
다음 경유로 사용
<Provider value={/* some value */}>
{children} /* potential consumers */
</Provider>
그리고.
<Consumer>
{value => /* render something based on the context value */}
</Consumer>
프로바이더의 하위인 모든 소비자는 프로바이더의 가치 제안이 변경될 때마다 다시 렌더링됩니다.공급자에서 하위 소비자로의 전파는 wouldComponentUpdate 메서드의 적용을 받지 않으므로 상위 구성 요소가 업데이트에서 벗어나더라도 소비자가 업데이트됩니다. 1
완전한 예, 반의사 코드.
import React from 'react';
const { Provider, Consumer } = React.createContext({ color: 'white' });
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
value: { color: 'black' },
};
}
render() {
return (
<Provider value={this.state.value}>
<Toolbar />
</Provider>
);
}
}
class Toolbar extends React.Component {
render() {
return (
<div>
<p> Consumer can be arbitrary levels deep </p>
<Consumer>
{value => <p> The toolbar will be in color {value.color} </p>}
</Consumer>
</div>
);
}
}
1 https://facebook.github.io/react/docs/context.html
중첩된 아이에게 소품 전달
React Hooks 업데이트를 통해 React.createContext 및 useContext를 사용할 수 있습니다.
import * as React from 'react';
// React.createContext accepts a defaultValue as the first param
const MyContext = React.createContext();
functional Parent(props) {
const doSomething = React.useCallback((value) => {
// Do something here with value
}, []);
return (
<MyContext.Provider value={{ doSomething }}>
{props.children}
</MyContext.Provider>
);
}
function Child(props: { value: number }) {
const myContext = React.useContext(MyContext);
return (
<div onClick={myContext.doSomething}>{props.value}</div>
);
}
// Example of using Parent and Child
import * as React from 'react';
function SomeComponent() {
return (
<Parent>
<Child value={1} />
<Child value={2} />
</Parent>
);
}
React.createContext는 React.cloneElement 케이스가 중첩된 컴포넌트를 처리할 수 없는 경우에 유효합니다.
function SomeComponent() {
return (
<Parent>
<Child value={1} />
<SomeOtherComp>
<Child value={2} />
</SomeOtherComp>
</Parent>
);
}
을 가능하게 좋은 방법은 「」입니다.children
함수 패턴처럼 https://medium.com/merrickchristensen/function-as-child-components-5f3920a9ace9
코드 스니펫 : https://stackblitz.com/edit/react-fcmubc
예:
const Parent = ({ children }) => {
const somePropsHere = {
style: {
color: "red"
}
// any other props here...
}
return children(somePropsHere)
}
const ChildComponent = props => <h1 {...props}>Hello world!</h1>
const App = () => {
return (
<Parent>
{props => (
<ChildComponent {...props}>
Bla-bla-bla
</ChildComponent>
)}
</Parent>
)
}
하시면 됩니다.React.cloneElement
어플리케이션에서 사용하기 전에 동작 방법을 알아두는 것이 좋습니다.되어 있습니다.React v0.13
세한것 、 을을해해요요 。★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
<div>{React.cloneElement(this.props.children, {...this.props})}</div>
React 문서의 각 행을 가져와 이 모든 것이 어떻게 작동하는지, 그리고 어떻게 사용할 수 있는지 이해하십시오.
React v0.13 RC2에서는 다음과 같은 시그니처를 가진 React.addons.cloneWithProps와 유사한 새로운 API를 소개합니다.
React.cloneElement(element, props, ...children);
클론과는 달리이 새로운 함수는 transferPropsTo에 없는 것과 같은 이유로 style과 className을 Marge하기 위한 매직인 동작을 하지 않습니다.매직의 전체 목록이 정확히 무엇인지 아무도 확신하지 못하기 때문에 코드에 대해 추론하기가 어렵고 스타일이 다른 시그니처를 가지고 있을 때(예: 곧 출시될 React Native에서) 재사용하기가 어렵습니다.
React.cloneElement는 다음과 거의 동일합니다.
<element.type {...element.props} {...props}>{children}</element.type>
단, JSX 및 클론과는 달리Props를 사용하면 참조도 보존됩니다.이것은 만약 당신이 레프가 있는 아이를 갖게 된다면, 당신은 실수로 당신의 조상으로부터 그것을 훔치지 않을 것이라는 것을 의미합니다.새 요소에 동일한 참조가 첨부됩니다.
한 가지 일반적인 패턴은 자녀에게 지도를 그려주고 새로운 소품을 추가하는 것입니다.클론에 관한 많은 문제가 보고되었습니다.Props가 refer를 잃었기 때문에 당신의 코드를 추론하는 것이 더 어려워졌습니다.이제 cloneElement에서도 같은 패턴을 따를 수 있습니다.예를 들어 다음과 같습니다.
var newChildren = React.Children.map(this.props.children, function(child) {
return React.cloneElement(child, { foo: true })
});
참고: React.cloneElement(하위, {ref: 'newRef' })는 참조를 재정의하므로 callback-ref를 사용하지 않는 한 두 상위 항목이 동일한 하위 항목에 대한 참조를 가질 수 없습니다.
이 기능은 현재 소품들이 불변하기 때문에 리액트 0.13에 들어가는 데 매우 중요한 기능이었다.업그레이드 경로는 종종 요소를 복제하는 것이지만, 그렇게 하면 참조가 손실될 수 있습니다.따라서 우리는 여기에 더 나은 업그레이드 경로가 필요했습니다.Facebook에서 콜사이트를 업그레이드하면서 이 방법이 필요하다는 것을 깨달았습니다.커뮤니티에서도 같은 피드백을 받았습니다.그래서 우리는 이것을 확실히 넣기 위해 최종 출시 전에 다른 RC를 만들기로 했습니다.
최종적으로 React.addons.cloneWithProps를 폐지할 예정입니다.아직 진행 중이지는 않지만, 이제는 자신의 용도에 대해 생각해보고 대신 React.cloneElement 사용을 고려해 볼 수 있는 좋은 기회입니다.실제로 제거하기 전에 반드시 권장 해제 통지와 함께 릴리즈를 발송하므로 즉각적인 조치는 필요하지 않습니다.
여기 더...
이 포인터가 아닌 저 포인터를 사용하여 작동하기 위해 위에서 수락한 답변을 수정해야 했습니다.맵 함수의 범위 내에는 doSomething 함수가 정의되어 있지 않습니다.
var Parent = React.createClass({
doSomething: function() {
console.log('doSomething!');
},
render: function() {
var that = this;
var childrenWithProps = React.Children.map(this.props.children, function(child) {
return React.cloneElement(child, { doSomething: that.doSomething });
});
return <div>{childrenWithProps}</div>
}})
업데이트: 이 수정은 ECMAScript 5용입니다. ES6에서는 var에 = this가 필요하지 않습니다.
텍스트 문자열과 같은 NOT React 구성 요소가 아닌 하위 구성 요소를 갖는 문제에 대한 답변은 없습니다.회피책은 다음과 같습니다.
// Render method of Parent component
render(){
let props = {
setAlert : () => {alert("It works")}
};
let childrenWithProps = React.Children.map( this.props.children, function(child) {
if (React.isValidElement(child)){
return React.cloneElement(child, props);
}
return child;
});
return <div>{childrenWithProps}</div>
}
한 명 이상의 자녀를 고려한 더 깨끗한 방법
<div>
{ React.Children.map(this.props.children, child => React.cloneElement(child, {...this.props}))}
</div>
방법 1 - 자녀 복제
const Parent = (props) => {
const attributeToAddOrReplace= "Some Value"
const childrenWithAdjustedProps = React.Children.map(props.children, child =>
React.cloneElement(child, { attributeToAddOrReplace})
);
return <div>{childrenWithAdjustedProps }</div>
}
방법 2 - 구성 가능한 컨텍스트 사용
Context를 사용하면 프로펠러를 소품으로 명시적으로 전달하지 않고 하위 컴포넌트에 프로펠러를 전달할 수 있습니다.
컨텍스트에는 다음과 같은 단점이 있습니다.
- 데이터는 소품을 통해 정기적으로 전송되지 않습니다.
- 콘텍스트를 사용하면 소비자와 공급자 간에 계약이 생성됩니다.컴포넌트를 재사용하는 데 필요한 요건을 이해하고 복제하는 것은 더 어려울 수 있습니다.
컴포지터블 컨텍스트 사용
export const Context = createContext<any>(null);
export const ComposableContext = ({ children, ...otherProps }:{children:ReactNode, [x:string]:any}) => {
const context = useContext(Context)
return(
<Context.Provider {...context} value={{...context, ...otherProps}}>{children}</Context.Provider>
);
}
function App() {
return (
<Provider1>
<Provider2>
<Displayer />
</Provider2>
</Provider1>
);
}
const Provider1 =({children}:{children:ReactNode}) => (
<ComposableContext greeting="Hello">{children}</ComposableContext>
)
const Provider2 =({children}:{children:ReactNode}) => (
<ComposableContext name="world">{children}</ComposableContext>
)
const Displayer = () => {
const context = useContext(Context);
return <div>{context.greeting}, {context.name}</div>;
};
Parent.jsx:
import React from 'react';
const doSomething = value => {};
const Parent = props => (
<div>
{
!props || !props.children
? <div>Loading... (required at least one child)</div>
: !props.children.length
? <props.children.type {...props.children.props} doSomething={doSomething} {...props}>{props.children}</props.children.type>
: props.children.map((child, key) =>
React.cloneElement(child, {...props, key, doSomething}))
}
</div>
);
Child.jsx:
import React from 'react';
/* but better import doSomething right here,
or use some flux store (for example redux library) */
export default ({ doSomething, value }) => (
<div onClick={() => doSomething(value)}/>
);
및 main.devx:
import React from 'react';
import { render } from 'react-dom';
import Parent from './Parent';
import Child from './Child';
render(
<Parent>
<Child/>
<Child value='1'/>
<Child value='2'/>
</Parent>,
document.getElementById('...')
);
다음 예시를 참조하십시오.https://plnkr.co/edit/jJHQECrKRrtKlKYRpIWl?p=preview
소품을 전달하려는 자녀가 여러 명 있는 경우 React를 사용하여 이 방법을 사용할 수 있습니다.Children.map:
render() {
let updatedChildren = React.Children.map(this.props.children,
(child) => {
return React.cloneElement(child, { newProp: newProp });
});
return (
<div>
{ updatedChildren }
</div>
);
}
컴포넌트에 자식이 1개밖에 없는 경우 매핑이 필요 없으며 cloneElement만 바로 실행할 수 있습니다.
render() {
return (
<div>
{
React.cloneElement(this.props.children, {
newProp: newProp
})
}
</div>
);
}
위의 모든 답변에서 영감을 얻었고 이것이 내가 한 일입니다.데이터 같은 소품이나 컴포넌트를 전달하고 있습니다.
import React from "react";
const Parent = ({ children }) => {
const { setCheckoutData } = actions.shop;
const { Input, FieldError } = libraries.theme.components.forms;
const onSubmit = (data) => {
setCheckoutData(data);
};
const childrenWithProps = React.Children.map(
children,
(child) =>
React.cloneElement(child, {
Input: Input,
FieldError: FieldError,
onSubmit: onSubmit,
})
);
return <>{childrenWithProps}</>;
};
@and_rest answer에 덧붙여, 이것은 아이를 복제해 클래스를 추가하는 방법입니다.
<div className="parent">
{React.Children.map(this.props.children, child => React.cloneElement(child, {className:'child'}))}
</div>
많은 사람들이 이 기능을 안티패턴으로 간주하고 있지만, 이 기능을 사용할 수 있는 것은 자신이 무엇을 하고 있는지 알고 솔루션을 잘 설계하면 가능한 것입니다.
이 시나리오에는 렌더 프로포트가 적절한 방법이라고 생각합니다.
다음과 같이 부모 코드를 리팩터링하여 부모 구성요소에 필요한 소품을 제공할 수 있습니다.
const Parent = ({children}) => {
const doSomething(value) => {}
return children({ doSomething })
}
그런 다음 하위 구성 요소에서 다음과 같이 부모가 제공하는 기능에 액세스할 수 있습니다.
class Child extends React {
onClick() => { this.props.doSomething }
render() {
return (<div onClick={this.onClick}></div>);
}
}
이제 피어널 구조는 다음과 같습니다.
<Parent>
{(doSomething) =>
(<Fragment>
<Child value="1" doSomething={doSomething}>
<Child value="2" doSomething={doSomething}>
<Fragment />
)}
</Parent>
싱글, 멀티 및 비장애인 자녀와 함께 사용할 수 있는 버전입니다.
const addPropsToChildren = (children, props) => {
const addPropsToChild = (child, props) => {
if (React.isValidElement(child)) {
return React.cloneElement(child, props);
} else {
console.log("Invalid element: ", child);
return child;
}
};
if (Array.isArray(children)) {
return children.map((child, ix) =>
addPropsToChild(child, { key: ix, ...props })
);
} else {
return addPropsToChild(children, props);
}
};
사용 예:
https://codesandbox.io/s/loving-mcclintock-59emq?file=/src/ChildVsChildren.jsx:0-1069
가장 교묘한 방법:
{React.cloneElement(this.props.children, this.props)}
『 』의 cloneElement()
React.cloneElement(
element,
[props],
[...children]
)
요소를 시작점으로 사용하여 새 React 요소를 복제하고 반환합니다.결과 요소에는 원래 요소의 소품과 새로운 소품이 얕게 결합됩니다.새로운 아이들이 기존의 아이들을 대신할 것이다.원래 요소의 키와 참조가 보존됩니다.
React.cloneElement()
는 거의.<element.type {...element.props} {...props}>{children}</element.type>
단, 참조도 보존합니다.이것은 만약 당신이 레프가 있는 아이를 갖게 된다면, 당신은 실수로 당신의 조상으로부터 그것을 훔치지 않을 것이라는 것을 의미합니다.새 요소에 동일한 참조가 첨부됩니다.
따라서 아이들에게 커스텀 소품을 제공하기 위해 사용할 수 있는 것이 cloneElement입니다., 수 . 외 은 ' 낫다'를 사용해서 .React.Children.map
단,하지만React.Children.map
와는 달리React.cloneElement
키와 키를 변경합니다..$
프리픽스로서 사용합니다.상세한 것에 대하여는, 다음의 질문을 참조해 주세요.React.cloneElement in React.Children.map으로 인해 요소 키가 변경되었습니다.
대신 하다'로.forEach
같은 기능을 하다
render() {
const newElements = [];
React.Children.forEach(this.props.children,
child => newElements.push(
React.cloneElement(
child,
{...this.props, ...customProps}
)
)
)
return (
<div>{newElements}</div>
)
}
더 필요 없어요.{this.props.children}
, 그럼 이제 아이 를 .를 사용해서 할 수 render
Route
평소처럼 소품을 건네주세요.
<BrowserRouter>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/posts">Posts</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
<hr/>
<Route path="/" exact component={Home} />
<Route path="/posts" render={() => (
<Posts
value1={1}
value2={2}
data={this.state.data}
/>
)} />
<Route path="/about" component={About} />
</div>
</BrowserRouter>
단일 자식 요소를 가진 모든 사용자는 이 작업을 수행해야 합니다.
{React.isValidElement(this.props.children)
? React.cloneElement(this.props.children, {
...prop_you_want_to_pass
})
: null}
컴포넌트를 할 때 하실 수 .TypeError: Cannot add property myNewProp, object is not extensible
하려고 할 때 가 발생합니다.props.children
소품을 복제하고 아이 자체를 새로운 소품으로 복제하는 작업이 있다.
const MyParentComponent = (props) => {
return (
<div className='whatever'>
{props.children.map((child) => {
const newProps = { ...child.props }
// set new props here on newProps
newProps.myNewProp = 'something'
const preparedChild = { ...child, props: newProps }
return preparedChild
})}
</div>
)
}
이게 당신이 원하는 건가요?
var Parent = React.createClass({
doSomething: function(value) {
}
render: function() {
return <div>
<Child doSome={this.doSomething} />
</div>
}
})
var Child = React.createClass({
onClick:function() {
this.props.doSome(value); // doSomething is undefined
},
render: function() {
return <div onClick={this.onClick}></div>
}
})
비슷한 니즈를 조사하면서 이 포스트에 왔지만, 너무 인기 있고, 너무 생소한 복제 솔루션이라 기능성에 대한 집중을 떨어뜨리고 있다고 느꼈습니다.
샘플은 다음과 같습니다.
import React from 'react';
const withForm = (ViewComponent) => {
return (props) => {
const myParam = "Custom param";
return (
<>
<div style={{border:"2px solid black", margin:"10px"}}>
<div>this is poc form</div>
<div>
<ViewComponent myParam={myParam} {...props}></ViewComponent>
</div>
</div>
</>
)
}
}
export default withForm;
const pocQuickView = (props) => {
return (
<div style={{border:"1px solid grey"}}>
<div>this is poc quick view and it is meant to show when mouse hovers over a link</div>
</div>
)
}
export default withForm(pocQuickView);
저는 고차 컴포넌트 패턴을 구현하기 위한 유연한 솔루션을 찾았습니다.
물론 기능에 따라 다르지만, 비슷한 요구 사항을 찾는 다른 사용자가 있다면 복제와 같은 원시 수준의 반응 코드에 의존하는 것보다 훨씬 좋습니다.
제가 자주 사용하는 다른 패턴은 컨테이너 패턴입니다. 읽어보세요. 기사도 많이 있습니다.
하나 또는 여러 개의 자 노드가 있는 TypeScript에서 이 작업을 올바르게 수행하는 방법을 궁금해하는 사람이 있는 경우.UUID 라이브러리를 사용하여 하위 요소의 고유한 키 속성을 생성하고 있습니다. 물론 하나의 요소만 복제하는 경우에는 필요하지 않습니다.
export type TParentGroup = {
value?: string;
children: React.ReactElement[] | React.ReactElement;
};
export const Parent = ({
value = '',
children,
}: TParentGroup): React.ReactElement => (
<div className={styles.ParentGroup}>
{Array.isArray(children)
? children.map((child) =>
React.cloneElement(child, { key: uuidv4(), value })
)
: React.cloneElement(children, { value })}
</div>
);
바와 이 에서는 의 배열을 합니다.ReactElement
또한 필요에 따라 속성을 하위 컴포넌트에 전달할 수도 있습니다.
리액트 아이들이 내 밑에서 일하지 않는 이유가 있어이게 나한테 효과가 있었어.
소품을 바꾸는 것과 비슷하게 아이에게 클래스를 추가하고 싶었다.
var newChildren = this.props.children.map((child) => {
const className = "MenuTooltip-item " + child.props.className;
return React.cloneElement(child, { className });
});
return <div>{newChildren}</div>;
여기서 중요한 것은 React.cloneElement입니다.비슷한 방법으로 어떤 소품이라도 건네줄 수 있습니다.
이 문제에 대한 가장 정확한 접근법은 렌더 소품입니다.자식 구성요소를 자식 소품으로 부모 구성요소에 전달하는 대신 부모가 자식 구성요소를 수동으로 렌더링하도록 합니다.렌더는 기능 매개변수를 사용하는 반응의 기본 제공 소품입니다.이 함수에서는 부모 컴포넌트가 커스텀 파라미터로 원하는 대로 렌더링 할 수 있습니다.기본적으로는 어린이 소품과 같은 기능을 하지만 커스터마이즈 할 수 있습니다.
class Child extends React.Component {
render() {
return <div className="Child">
Child
<p onClick={this.props.doSomething}>Click me</p>
{this.props.a}
</div>;
}
}
class Parent extends React.Component {
doSomething(){
alert("Parent talks");
}
render() {
return <div className="Parent">
Parent
{this.props.render({
anythingToPassChildren:1,
doSomething: this.doSomething})}
</div>;
}
}
class Application extends React.Component {
render() {
return <div>
<Parent render={
props => <Child {...props} />
}/>
</div>;
}
}
이렇게 하는 방법은 여러 가지가 있습니다.
부모에게 아이들을 소품으로 넘겨줄 수 있다.
예 1:
function Parent({ChildElement}){
return <ChildElement propName={propValue} />
}
return <Parent ChildElement={ChildComponent}/>
하위 항목을 함수로 전달
예 2:
function Parent({children}){
return children({className: "my_div"})
}
OR
function Parent({children}){
let Child = children
return <Child className='my_div' />
}
function Child(props){
return <div {...props}></div>
}
export <Parent>{props => <Child {...props} />}</Parent>
나열된 답변이 작동하도록 노력했지만 실패했습니다.결국 부모-자녀 관계를 올바르게 설정하는 것이 문제라는 것을 알게 되었습니다.단순히 다른 컴포넌트 안에 컴포넌트를 네스트한다고 해서 부모-자녀 관계가 있는 것은 아닙니다.
예 1. 부모-자녀 관계
function Wrapper() {
return (
<div>
<OuterComponent>
<InnerComponent />
</OuterComponent>
</div>
);
}
function OuterComponent(props) {
return props.children;
}
function InnerComponent() {
return <div>Hi! I'm in inner component!</div>;
}
export default Wrapper;
예 2중첩된 구성 요소:
function Wrapper() {
return (
<div>
<OuterComponent />
</div>
);
}
function OuterComponent(props) {
return <InnerComponent />
}
function InnerComponent() {
return <div>Hi! I'm in inner component!</div>;
}
export default Wrapper;
앞에서 말씀드린 바와 같이 사례 1에서는 소품 패싱이 효과적입니다.
다음 기사에서는 https://medium.com/@justynazet/sublic-to-sublic-children-using-clone-and-sublic-pattern-896da70b24f6에 대해 설명합니다.
언급URL : https://stackoverflow.com/questions/32370994/how-to-pass-props-to-this-props-children
'programing' 카테고리의 다른 글
Flask Web App 도킹 후 정기적인 "쿼리 중 MySQL 서버 연결 끊김" (0) | 2022.11.23 |
---|---|
mysql 랜덤 정수 범위를 가져오려면 어떻게 해야 합니까? (0) | 2022.11.23 |
변수 선언에 'var'를 사용하는 것은 옵션입니까? (0) | 2022.11.23 |
분배, 디스트리뷰트, 세트툴 및 디스트리뷰트2의 차이점 (0) | 2022.11.23 |
자바에서 JSON을 유창하게 구축하는 방법은? (0) | 2022.11.23 |