Development Tip

React.js — 속성 객체를 자식 컴포넌트에 전달하는 방법은 무엇입니까?

yourdevel 2020. 10. 31. 10:12
반응형

React.js — 속성 객체를 자식 컴포넌트에 전달하는 방법은 무엇입니까?


tileGroup다른 속성의 모음 (배열) 인 속성 이있는 구성 요소 가 있습니다.

부모 component ( tileGroup)는 컬렉션의 각 속성 집합을 사용하여 새 구성 요소를 생성하여 자식 구성 요소 목록을 렌더링합니다.

지금은 각 속성을 집합에서 자식 구성 요소로 개별적으로 매핑하고 있지만 구성 요소의 속성 수가 증가하면 복잡해지고 더 깔끔하고 간단한 방법이 있다고 확신합니다.

각 속성을 다시 매핑하지 않고 전체 속성 집합을 자식 구성 요소에 전달하려면 어떻게해야합니까?

예제 코드 :

tileGroupData = {someProperty: 'something', someOtherProperty:'something', 
                tiles: [{vsize:1, hsize:2, etc...}, {vsize:2,hsize:3,title:'whatever'}]};

그런 다음 구성 요소 생성 ..

var tileGroup = React.createClass({
    render: function() {
       var thechildren = this.props.tiles.map(function(tile)
       {
           //this is what I DON'T want to be doing. 
           return <tileSimple vsize = {tile.vsize} hsize = {tile.hsize} content = {tile.content}/>;

           //what I DO want to be doing
           return <tileSimple allTheProps = {tile}/>; 
       });

분명히 transferPropsTo는 더 이상 사용되지 않습니다. 최신 버전의 React에서는 JSX 스프레드 속성을 사용할 수 있습니다.

return <tileSimple {...tile} />;

여기에 대한 자세한 정보 : transferPropsTo 지원 중단


이러한 사용 사례의 경우 가장 쉬운 방법은 JSX 대신 JS API로 대체하는 것입니다.

return tileSimple(tile);

작동 이유를 이해하려면 JSX 컴파일러 도구 ( http://facebook.github.io/react/jsx-compiler.html )를 사용하여 원하는 버전의 생성 된 버전을 확인하십시오.

<tileSimple vsize = {tile.vsize} hsize = {tile.hsize} content = {tile.content}/>;
tileSimple( {vsize:  tile.vsize, hsize:  tile.hsize, content:  tile.content});

실제로 렌더링에서 다음을 수행 할 수 있습니다.

return this.transferPropsTo(<tileSimple />);

당신이 제안하는 것,

return <tileSimple allTheProps={tile} />;

잘 작동합니다.

tileSimple구성 요소 내에서 다음과 같은 구문을 사용하여 속성에 액세스 할 수 있어야합니다.

var vsize = this.props.allTheProps.vsize;
var hsize = this.props.allTheProps.hsize;

참고 URL : https://stackoverflow.com/questions/20913288/react-js-how-to-pass-properties-object-to-child-component

반응형